pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Reducing the chunk header sizes on all memory context types
152+ messages / 11 participants
[nested] [flat]

Commits from this thread:
  2022-09-07 5265e91fd1  Make MemoryContextContains work correctly again
  2022-09-07 0e480385ec  Make more effort to put a sentinel at the end of allocated memory
  2022-08-30 05f9084236  Various cleanups of the new memory context header code
  2022-08-30 5495796ad1  Revert "Add missing padding from MemoryChunk struct"
  2022-08-29 c6e0fe1f2a  Improve performance of and reduce overheads of memory management
* Reducing the chunk header sizes on all memory context types
@ 2022-07-12 05:01  David Rowley <dgrowleyml@gmail.com>
  0 siblings, 2 replies; 152+ messages in thread

From: David Rowley @ 2022-07-12 05:01 UTC (permalink / raw)
  To: PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Over on [1], I highlighted that 40af10b57 (Use Generation memory
contexts to store tuples in sorts) could cause some performance
regressions for sorts when the size of the tuple is exactly a power of
2.  The reason for this is that the chunk header for generation.c
contexts is 8 bytes larger (on 64-bit machines) than the aset.c chunk
header. This means that we can store fewer tuples per work_mem during
the sort and that results in more batches being required.

As I write this, this regression is still marked as an open item for
PG15 in [2]. So I've been working on this to try to assist the
discussion about if we need to do anything about that for PG15.

Over on [3], I mentioned that Andres came up with an idea and a
prototype patch to reduce the chunk header size across the board by
storing the context type in the 3 least significant bits in a uint64
header.

I've taken Andres' patch and made some quite significant changes to
it. In the patch's current state, the sort performance regression in
PG15 vs PG14 is fixed. The generation.c context chunk header has been
reduced to 8 bytes from the previous 24 bytes as it is in master.
aset.c context chunk header is now 8 bytes instead of 16 bytes.

We can use this 8-byte chunk header by using the remaining 61-bits of
the uint64 header to encode 2 30-bit values to store the chunk size
and also the number of bytes we must subtract from the given pointer
to find the block that the chunk is stored on.  Once we have the
block, we can find the owning context by having a pointer back to the
context from the block.  For memory allocations that are larger than
what can be stored in 30 bits, the chunk header gets an additional two
Size fields to store the chunk_size and the block offset.  We can tell
the difference between the 2 chunk sizes by looking at the spare 1-bit
the uint64 portion of the header.

Aside from speeding up the sort case, this also seems to have a good
positive performance impact on pgbench read-only workload with -M
simple. I'm seeing about a 17% performance increase on my AMD
Threadripper machine.

master + Reduced Memory Context Chunk Overhead
drowley@amd3990x:~$ pgbench -S -T 60 -j 156 -c 156 -M simple postgres
tps = 1876841.953096 (without initial connection time)
tps = 1919605.408254 (without initial connection time)
tps = 1891734.480141 (without initial connection time)

Master
drowley@amd3990x:~$ pgbench -S -T 60 -j 156 -c 156 -M simple postgres
tps = 1632248.236962 (without initial connection time)
tps = 1615663.151604 (without initial connection time)
tps = 1602004.146259 (without initial connection time)

The attached .png file shows the same results for PG14 and PG15 as I
showed in the blog [4] where I discovered the regression and adds the
results from current master + the attached patch. See bars in orange.
You can see that the regression at 64MB work_mem is fixed. Adding some
tracing to the sort shows that we're now doing 671745 tuples per batch
instead of 576845 tuples. This reduces the number of batches from 245
down to 210.

Drawbacks:

There is at least one. It might be major; to reduce the AllocSet chunk
header from 16 bytes down to 8 bytes I had to get rid of the freelist
pointer that was reusing the "aset" field in the chunk header struct.
This works now by storing that pointer in the actual palloc'd memory.
This could lead to pretty hard-to-trace bugs if we have any code that
accidentally writes to memory after pfree.  The slab.c context already
does this, but that's far less commonly used.  If we decided this was
unacceptable then it does not change anything for the generation.c
context.  The chunk header will still be 8 bytes instead of 24 there.
So the sort performance regression will still be fixed.

To improve this situation, we might be able code it up so that
MEMORY_CONTEXT_CHECKING builds add an additional freelist pointer to
the header and also write it to the palloc'd memory then verify
they're set to the same thing when we reuse a chunk from the freelist.
If they're not the same then MEMORY_CONTEXT_CHECKING builds could
either spit out a WARNING or ERROR for this case.  That would make it
pretty easy for developers to find their write after pfree bugs. This
might actually be better than the Valgrind  detection method that we
have for this today.

Patch:

I've attached the WIP patch. At this stage, I'm more looking for a
design review. I'm not aware of any bugs, but I am aware that I've not
tested with Valgrind. I've not paid a great deal of attention to
updating the Valgrind macros at all.

I'll add this to the September CF.  I'm submitting now due to the fact
that we still have an open item in PG15 for the sort regression and
the existence of this patch might cause us to decide whether we can
defer fixing that to PG16 by way of the method in this patch, or
revert 40af10b57.

Benchmark code in [5].

David

[1] https://www.postgresql.org/message-id/CAApHDvqXpLzav6dUeR5vO_RBh_feHrHMLhigVQXw9jHCyKP9PA%40mail.gma...
[2] https://wiki.postgresql.org/wiki/PostgreSQL_15_Open_Items
[3] https://www.postgresql.org/message-id/CAApHDvowHNSVLhMc0cnovg8PfnYQZxit-gP_bn3xkT4rZX3G0w%40mail.gma...
[4] https://techcommunity.microsoft.com/t5/azure-database-for-postgresql/speeding-up-sort-performance-in...
[5] https://www.postgresql.org/message-id/attachment/134161/sortbench_varcols.sh

Attachments:

v1-0001-WIP-Reduce-memory-context-overheads.patch (text/plain, 109.6K) download From c5dd1fcd062a7eef9537302b931a8ab5a56c52a8 Mon Sep 17 00:00:00 2001 From: David Rowley <dgrowley@gmail.com> Date: Thu, 9 Jun 2022 20:09:22 +1200 Subject: [PATCH v1] WIP: Reduce memory context overheads Whenever we palloc a chunk of memory, traditionally, we prefix the returned pointer with a pointer to the memory context which the chunk belongs to. This is required so that we're able to easily determine the owning context when performing operations such as pfree() and repalloc(). The AllocSet context additionally prefixes the pointer to the owning context with the size of the chunk which makes the header 16 bytes in size. For generation contexts, the problem was worse. In addition to the pointer to the owning context, we also stored a pointer to the owning block then prefixed the chunk size, which resulted in a 24-byte header. Here we completely change the rule that pointers must be directly prefixed by the owning memory context and instead, insist that they're directly prefixed by a uint64 variable where the least significant 3-bits are set to a value to indicate which type of memory context the pointer belongs to. We're then able to pass the pointer to the function specific to that context implementation to allow it to determine the actual memory context to which the pointer belongs. Here we implement a general-purpose way of encoding the remaining bits in the prefixing uint64 value which allows encoding of the chunk size and also the number of bytes to subtract from the pointer to get a pointer to the block the pointer belongs to. All memory contexts now subtract the block offset bytes to obtain a pointer to the block and that block contains a pointer to the owning context. This means we only store a pointer to the context once per block, rather than once per chunk as we did previously. Because the remaining space in the prefixing uint64 value after storing the 3-bit value to indicate the memory context type is only 61 bits, we only have 30 bits each to store the chunk size and the block offset values. We do allow much larger allocations than what can be stored in 30 bits, so we also have a concept of a "large" chunk and we mark if the chunk is small or large with the 1 remaining bit in the uint64 header. When a chunk is large, the uint64 header value is immediately preceded by two Size values, one to indicate the chunk size and one for the block offset. For MEMORY_CONTEXT_CHECKING builds, each chunk header is prefixed by the number of bytes in the memory request. This allows us to perform all of the memory context checking still. --- src/backend/utils/mmgr/README | 59 ++- src/backend/utils/mmgr/aset.c | 618 ++++++++++++------------ src/backend/utils/mmgr/generation.c | 407 +++++++--------- src/backend/utils/mmgr/mcxt.c | 94 +++- src/backend/utils/mmgr/slab.c | 281 +++++------ src/include/nodes/memnodes.h | 7 +- src/include/utils/memutils.h | 48 +- src/include/utils/memutils_generichdr.h | 265 ++++++++++ src/include/utils/memutils_internal.h | 117 +++++ 9 files changed, 1140 insertions(+), 756 deletions(-) create mode 100644 src/include/utils/memutils_generichdr.h create mode 100644 src/include/utils/memutils_internal.h diff --git a/src/backend/utils/mmgr/README b/src/backend/utils/mmgr/README index 221b4bd343..58a2c5fc3d 100644 --- a/src/backend/utils/mmgr/README +++ b/src/backend/utils/mmgr/README @@ -378,35 +378,54 @@ MemoryContext like the parent and child contexts, and the name of the context. This is essentially an abstract superclass, and the behavior is -determined by the "methods" pointer is its virtual function table -(struct MemoryContextMethods). Specific memory context types will use -derived structs having these fields as their first fields. All the +determined by the "methods" pointer which references which set of +MemoryContextMethods are to be used. Specific memory context types will +use derived structs having these fields as their first fields. All the contexts of a specific type will have methods pointers that point to -the same static table of function pointers. +the corresponding element in the mcxt_methods[] array. While operations like allocating from and resetting a context take the relevant MemoryContext as a parameter, operations like free and realloc are trickier. To make those work, we require all memory context types to produce allocated chunks that are immediately, -without any padding, preceded by a pointer to the corresponding -MemoryContext. +without any padding, preceded by a uint64 value of which the least +significant 3 bits are set to the owning context's MemoryContextMethodID. +This allows the code to determine the correct MemoryContextMethods to +use by looking up the mcxt_methods[] array using the 3 bits as an index +into that array. If a type of allocator needs additional information about its chunks, like e.g. the size of the allocation, that information can in turn -precede the MemoryContext. This means the only overhead implied by -the memory context mechanism is a pointer to its context, so we're not -constraining context-type designers very much. - -Given this, routines like pfree determine their corresponding context -with an operation like (although that is usually encapsulated in -GetMemoryChunkContext()) - - MemoryContext context = *(MemoryContext*) (((char *) pointer) - sizeof(void *)); - -and then invoke the corresponding method for the context - - context->methods->free_p(pointer); - +either be encoded into the remaining 61 bits of the preceding uint64 value +or if more space is required, additional values may be stored directly prior +to the uint64 value. It is up to the context implementation to manage this. + +Given this, routines like pfree can determine which set of +MemoryContextMethods to call the free_p function for by calling +GetMemoryChunkMethodID() and finding the corresponding MemoryContextMethods +in the mcxt_methods array[]. For convenience, the MCXT_METHOD() macro is +provided, making the code as simple as: + +void +pfree(void *pointer) +{ + MCXT_METHOD(pointer, free_p)(pointer); +} + +All of the current memory contexts make use of a generic chunk header type +which is defined in memutils_generichdr.h. This suits all of the existing +context types well as it makes use of the remaining 61-bits of the uint64 +header to efficiently encode the size of the chunk of memory and the number +of bytes which must be subtracted from the pointer in order to obtain a +reference to the block that the pointer belongs to. 30 bits are used for each +of these. If more than 30 bits are required (i.e. > 1GB) then a "large" chunk +header is used which uses an additional two Size fields in the preceding +memory. All memory context implementations store a pointer back to the owning +context within the block and we can find that block by subtracting the block +offset bytes, as is stored in the generic header. During operations like +pfree, this allows memory contexts such as the generation context to track how +many chunks have been freed from a given block and then release the memory for +the block when all chunks have been freed. More Control Over aset.c Behavior --------------------------------- diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index ec3e264a73..f88d506cc1 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -49,6 +49,8 @@ #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_generichdr.h" +#include "utils/memutils_internal.h" /*-------------------- * Chunk freelist k holds chunks of size 1 << (k + ALLOC_MINBITS), @@ -66,7 +68,9 @@ * CAUTION: ALLOC_MINBITS must be large enough so that * 1<<ALLOC_MINBITS is at least MAXALIGN, * or we may fail to align the smallest chunks adequately. - * 8-byte alignment is enough on all currently known machines. + * 8-byte alignment is enough on all currently known machines. This 8-byte + * minimum also allows us to store a pointer to the next freelist item within + * the chunk of memory itself. * * With the current parameters, request sizes up to 8K are treated as chunks, * larger requests go into dedicated blocks. Change ALLOCSET_NUM_FREELISTS @@ -98,10 +102,8 @@ */ #define ALLOC_BLOCKHDRSZ MAXALIGN(sizeof(AllocBlockData)) -#define ALLOC_CHUNKHDRSZ sizeof(struct AllocChunkData) typedef struct AllocBlockData *AllocBlock; /* forward reference */ -typedef struct AllocChunkData *AllocChunk; /* * AllocPointer @@ -123,7 +125,7 @@ typedef struct AllocSetContext MemoryContextData header; /* Standard memory-context fields */ /* Info about storage allocated in this context: */ AllocBlock blocks; /* head of list of blocks in this set */ - AllocChunk freelist[ALLOCSET_NUM_FREELISTS]; /* free chunk lists */ + void *freelist[ALLOCSET_NUM_FREELISTS]; /* free pointer lists */ /* Allocation parameters for this context: */ Size initBlockSize; /* initial block size */ Size maxBlockSize; /* maximum block size */ @@ -139,11 +141,11 @@ typedef AllocSetContext *AllocSet; /* * AllocBlock * An AllocBlock is the unit of memory that is obtained by aset.c - * from malloc(). It contains one or more AllocChunks, which are - * the units requested by palloc() and freed by pfree(). AllocChunks - * cannot be returned to malloc() individually, instead they are put - * on freelists by pfree() and re-used by the next palloc() that has - * a matching request size. + * from malloc(). It contains one or more allocated chunks of memory, + * which are the units requested by palloc() and freed by pfree(). + * Chunks allocated by palloc cannot be returned to malloc() + * individually, instead they are put on freelists by pfree() and re-used + * by the next palloc() that has a matching chunk size. * * AllocBlockData is the header data for a block --- the usable space * within the block begins at the next alignment boundary. @@ -153,54 +155,11 @@ typedef struct AllocBlockData AllocSet aset; /* aset that owns this block */ AllocBlock prev; /* prev block in aset's blocks list, if any */ AllocBlock next; /* next block in aset's blocks list, if any */ + bool large_chunk; /* true if the only chunk is a large chunk */ char *freeptr; /* start of free space in this block */ char *endptr; /* end of space in this block */ } AllocBlockData; -/* - * AllocChunk - * The prefix of each piece of memory in an AllocBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "aset" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). We simplify matters for this - * module by requiring sizeof(AllocChunkData) to be maxaligned, and then - * we can ensure things work by adding any required alignment padding before - * the "aset" field. There is a static assertion below that the alignment - * is done correctly. - */ -typedef struct AllocChunkData -{ - /* size is always the size of the usable space in the chunk */ - Size size; -#ifdef MEMORY_CONTEXT_CHECKING - /* when debugging memory usage, also store actual requested size */ - /* this is zero in a free chunk */ - Size requested_size; - -#define ALLOCCHUNK_RAWSIZE (SIZEOF_SIZE_T * 2 + SIZEOF_VOID_P) -#else -#define ALLOCCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P) -#endif /* MEMORY_CONTEXT_CHECKING */ - - /* ensure proper alignment by adding padding if needed */ -#if (ALLOCCHUNK_RAWSIZE % MAXIMUM_ALIGNOF) != 0 - char padding[MAXIMUM_ALIGNOF - ALLOCCHUNK_RAWSIZE % MAXIMUM_ALIGNOF]; -#endif - - /* aset is the owning aset if allocated, or the freelist link if free */ - void *aset; - /* there must not be any padding to reach a MAXALIGN boundary here! */ -} AllocChunkData; - -/* - * Only the "aset" field should be accessed outside this module. - * We keep the rest of an allocated chunk's header marked NOACCESS when using - * valgrind. But note that chunk headers that are in a freelist are kept - * accessible, for simplicity. - */ -#define ALLOCCHUNK_PRIVATE_LEN offsetof(AllocChunkData, aset) - /* * AllocPointerIsValid * True iff pointer is valid allocation pointer. @@ -213,11 +172,6 @@ typedef struct AllocChunkData */ #define AllocSetIsValid(set) PointerIsValid(set) -#define AllocPointerGetChunk(ptr) \ - ((AllocChunk)(((char *)(ptr)) - ALLOC_CHUNKHDRSZ)) -#define AllocChunkGetPointer(chk) \ - ((AllocPointer)(((char *)(chk)) + ALLOC_CHUNKHDRSZ)) - /* * Rather than repeatedly creating and deleting memory contexts, we keep some * freed contexts in freelists so that we can hand them out again with little @@ -260,42 +214,6 @@ static AllocSetFreeList context_freelists[2] = } }; -/* - * These functions implement the MemoryContext API for AllocSet contexts. - */ -static void *AllocSetAlloc(MemoryContext context, Size size); -static void AllocSetFree(MemoryContext context, void *pointer); -static void *AllocSetRealloc(MemoryContext context, void *pointer, Size size); -static void AllocSetReset(MemoryContext context); -static void AllocSetDelete(MemoryContext context); -static Size AllocSetGetChunkSpace(MemoryContext context, void *pointer); -static bool AllocSetIsEmpty(MemoryContext context); -static void AllocSetStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); - -#ifdef MEMORY_CONTEXT_CHECKING -static void AllocSetCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for AllocSet contexts. - */ -static const MemoryContextMethods AllocSetMethods = { - AllocSetAlloc, - AllocSetFree, - AllocSetRealloc, - AllocSetReset, - AllocSetDelete, - AllocSetGetChunkSpace, - AllocSetIsEmpty, - AllocSetStats -#ifdef MEMORY_CONTEXT_CHECKING - ,AllocSetCheck -#endif -}; - /* ---------- * AllocSetFreeIndex - @@ -387,13 +305,6 @@ AllocSetContextCreateInternal(MemoryContext parent, AllocSet set; AllocBlock block; - /* Assert we padded AllocChunkData properly */ - StaticAssertStmt(ALLOC_CHUNKHDRSZ == MAXALIGN(ALLOC_CHUNKHDRSZ), - "sizeof(AllocChunkData) is not maxaligned"); - StaticAssertStmt(offsetof(AllocChunkData, aset) + sizeof(MemoryContext) == - ALLOC_CHUNKHDRSZ, - "padding calculation in AllocChunkData is wrong"); - /* * First, validate allocation parameters. Once these were regular runtime * test and elog's, but in practice Asserts seem sufficient because nobody @@ -409,6 +320,7 @@ AllocSetContextCreateInternal(MemoryContext parent, (minContextSize == MAXALIGN(minContextSize) && minContextSize >= 1024 && minContextSize <= maxBlockSize)); + Assert(maxBlockSize <= SMALL_CHUNK_LIMIT); /* * Check whether the parameters match either available freelist. We do @@ -443,7 +355,7 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Reinitialize its header, installing correct name and parent */ MemoryContextCreate((MemoryContext) set, T_AllocSetContext, - &AllocSetMethods, + MCTX_ASET_ID, parent, name); @@ -456,7 +368,7 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Determine size of initial block */ firstBlockSize = MAXALIGN(sizeof(AllocSetContext)) + - ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ; + ALLOC_BLOCKHDRSZ + SMALL_CHUNK_SIZE; if (minContextSize != 0) firstBlockSize = Max(firstBlockSize, minContextSize); else @@ -486,6 +398,7 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Fill in the initial block's block header */ block = (AllocBlock) (((char *) set) + MAXALIGN(sizeof(AllocSetContext))); block->aset = set; + block->large_chunk = false; block->freeptr = ((char *) block) + ALLOC_BLOCKHDRSZ; block->endptr = ((char *) set) + firstBlockSize; block->prev = NULL; @@ -519,22 +432,23 @@ AllocSetContextCreateInternal(MemoryContext parent, * * We have to have allocChunkLimit a power of two, because the requested * and actually-allocated sizes of any chunk must be on the same side of - * the limit, else we get confused about whether the chunk is "big". + * the limit, else we get confused about whether the chunk is large. * * Also, allocChunkLimit must not exceed ALLOCSET_SEPARATE_THRESHOLD. */ StaticAssertStmt(ALLOC_CHUNK_LIMIT == ALLOCSET_SEPARATE_THRESHOLD, "ALLOC_CHUNK_LIMIT != ALLOCSET_SEPARATE_THRESHOLD"); - set->allocChunkLimit = ALLOC_CHUNK_LIMIT; - while ((Size) (set->allocChunkLimit + ALLOC_CHUNKHDRSZ) > + /* We always want to allocate non-dedicated blocks as small chunks */ + set->allocChunkLimit = Min(ALLOC_CHUNK_LIMIT, SMALL_CHUNK_LIMIT); + while ((Size) (set->allocChunkLimit + SMALL_CHUNK_SIZE) > (Size) ((maxBlockSize - ALLOC_BLOCKHDRSZ) / ALLOC_CHUNK_FRACTION)) set->allocChunkLimit >>= 1; /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) set, T_AllocSetContext, - &AllocSetMethods, + MCTX_ASET_ID, parent, name); @@ -555,7 +469,7 @@ AllocSetContextCreateInternal(MemoryContext parent, * thrash malloc() when a context is repeatedly reset after small allocations, * which is typical behavior for per-tuple contexts. */ -static void +void AllocSetReset(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -623,7 +537,7 @@ AllocSetReset(MemoryContext context) * * Unlike AllocSetReset, this *must* free all resources of the set. */ -static void +void AllocSetDelete(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -717,15 +631,15 @@ AllocSetDelete(MemoryContext context) * is marked, as mcxt.c will set it to UNDEFINED. In some paths we will * return space that is marked NOACCESS - AllocSetRealloc has to beware! */ -static void * +void * AllocSetAlloc(MemoryContext context, Size size) { AllocSet set = (AllocSet) context; AllocBlock block; - AllocChunk chunk; int fidx; Size chunk_size; Size blksize; + void *pointer; AssertArg(AllocSetIsValid(set)); @@ -735,8 +649,12 @@ AllocSetAlloc(MemoryContext context, Size size) */ if (size > set->allocChunkLimit) { + Size genhdrsize; + chunk_size = MAXALIGN(size); - blksize = chunk_size + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ; + /* err on the side of caution and assume it'll be a large chunk */ + genhdrsize = GenericChunkHeaderSize(ALLOC_BLOCKHDRSZ + LARGE_CHUNK_SIZE, chunk_size); + blksize = ALLOC_BLOCKHDRSZ + genhdrsize + chunk_size; block = (AllocBlock) malloc(blksize); if (block == NULL) return NULL; @@ -744,20 +662,25 @@ AllocSetAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; block->aset = set; + /* mark if this is a large chunk or not */ + block->large_chunk = (genhdrsize == LARGE_CHUNK_SIZE); block->freeptr = block->endptr = ((char *) block) + blksize; - chunk = (AllocChunk) (((char *) block) + ALLOC_BLOCKHDRSZ); - chunk->aset = set; - chunk->size = chunk_size; + pointer = (void *) (((char *) block) + ALLOC_BLOCKHDRSZ + genhdrsize); + #ifdef MEMORY_CONTEXT_CHECKING - chunk->requested_size = size; + GenericChunkHeaderEncode(pointer, block, chunk_size, size, MCTX_ASET_ID); + /* set mark to catch clobber of "unused" space */ if (size < chunk_size) - set_sentinel(AllocChunkGetPointer(chunk), size); + set_sentinel(pointer, size); +#else + GenericChunkHeaderEncode(pointer, block, chunk_size, MCTX_ASET_ID); #endif + #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) pointer, size); #endif /* @@ -780,13 +703,12 @@ AllocSetAlloc(MemoryContext context, Size size) } /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS(((char *) pointer) + size, chunk_size - size); - /* Disallow external access to private part of chunk header. */ - VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); + Assert(GetMemoryChunkMethodID(pointer) == MCTX_ASET_ID); - return AllocChunkGetPointer(chunk); + return pointer; } /* @@ -796,42 +718,59 @@ AllocSetAlloc(MemoryContext context, Size size) * of the alloc set and return its data address. */ fidx = AllocSetFreeIndex(size); - chunk = set->freelist[fidx]; - if (chunk != NULL) - { - Assert(chunk->size >= size); - set->freelist[fidx] = (AllocChunk) chunk->aset; + /* + * Choose the actual chunk size to allocate. + */ + chunk_size = (1 << ALLOC_MINBITS) << fidx; + Assert(chunk_size >= size); - chunk->aset = (void *) set; + pointer = set->freelist[fidx]; + if (pointer != NULL) + { + /* + * Point the freelist head at the next free chunk which we stored in + * the allocated memory + */ + set->freelist[fidx] = *((void **) pointer); #ifdef MEMORY_CONTEXT_CHECKING - chunk->requested_size = size; + { + /* + * The chunk header is already set correctly when not doing + * MEMORY_CONTEXT_CHECKING. Here we just need to update the + * requested size. We must decode it to get the block offset + * before we reencode it again. + */ + AllocBlock block; + Size chksz, blkoff, reqsz; + + GenericChunkHeaderDecode(pointer, &chksz, &blkoff, &reqsz); + + block = (AllocBlock) ((char *) pointer - blkoff); + + GenericChunkHeaderEncode(pointer, block, chunk_size, size, MCTX_ASET_ID); + } + /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(AllocChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(pointer, size); #endif + #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) pointer, size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, - chunk->size - size); + VALGRIND_MAKE_MEM_NOACCESS(((char *) pointer) + size, + chunk_size - size); - /* Disallow external access to private part of chunk header. */ - VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); + Assert(GetMemoryChunkMethodID(pointer) == MCTX_ASET_ID); - return AllocChunkGetPointer(chunk); + return pointer; } - /* - * Choose the actual chunk size to allocate. - */ - chunk_size = (1 << ALLOC_MINBITS) << fidx; - Assert(chunk_size >= size); - /* * If there is enough room in the active allocation block, we will put the * chunk into that block. Else must start a new one. @@ -840,7 +779,9 @@ AllocSetAlloc(MemoryContext context, Size size) { Size availspace = block->endptr - block->freeptr; - if (availspace < (chunk_size + ALLOC_CHUNKHDRSZ)) + Assert(availspace <= SMALL_CHUNK_LIMIT); + + if (availspace < (SMALL_CHUNK_SIZE + chunk_size)) { /* * The existing active (top) block does not have enough room for @@ -854,9 +795,9 @@ AllocSetAlloc(MemoryContext context, Size size) * ALLOC_CHUNK_LIMIT left in the block, this loop cannot iterate * more than ALLOCSET_NUM_FREELISTS-1 times. */ - while (availspace >= ((1 << ALLOC_MINBITS) + ALLOC_CHUNKHDRSZ)) + while (availspace >= ((1 << ALLOC_MINBITS) + SMALL_CHUNK_SIZE + sizeof(void *))) { - Size availchunk = availspace - ALLOC_CHUNKHDRSZ; + Size availchunk = availspace - SMALL_CHUNK_SIZE; int a_fidx = AllocSetFreeIndex(availchunk); /* @@ -871,22 +812,21 @@ AllocSetAlloc(MemoryContext context, Size size) availchunk = ((Size) 1 << (a_fidx + ALLOC_MINBITS)); } - chunk = (AllocChunk) (block->freeptr); - - /* Prepare to initialize the chunk header. */ - VALGRIND_MAKE_MEM_UNDEFINED(chunk, ALLOC_CHUNKHDRSZ); + pointer = (void *) (block->freeptr + SMALL_CHUNK_SIZE); - block->freeptr += (availchunk + ALLOC_CHUNKHDRSZ); - availspace -= (availchunk + ALLOC_CHUNKHDRSZ); + block->freeptr += (availchunk + SMALL_CHUNK_SIZE); + availspace -= (availchunk + SMALL_CHUNK_SIZE); - chunk->size = availchunk; #ifdef MEMORY_CONTEXT_CHECKING - chunk->requested_size = 0; /* mark it free */ + /* mark it free */ + GenericChunkHeaderEncode(pointer, block, availchunk, 0, MCTX_ASET_ID); +#else + GenericChunkHeaderEncode(pointer, block, availchunk, MCTX_ASET_ID); #endif - chunk->aset = (void *) set->freelist[a_fidx]; - set->freelist[a_fidx] = chunk; + /* push this chunk onto the freelist */ + *((void **) pointer) = set->freelist[a_fidx]; + set->freelist[a_fidx] = pointer; } - /* Mark that we need to create a new block */ block = NULL; } @@ -912,7 +852,7 @@ AllocSetAlloc(MemoryContext context, Size size) * If initBlockSize is less than ALLOC_CHUNK_LIMIT, we could need more * space... but try to keep it a power of 2. */ - required_size = chunk_size + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ; + required_size = ALLOC_BLOCKHDRSZ + SMALL_CHUNK_SIZE + chunk_size; while (blksize < required_size) blksize <<= 1; @@ -937,6 +877,7 @@ AllocSetAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; block->aset = set; + block->large_chunk = false; block->freeptr = ((char *) block) + ALLOC_BLOCKHDRSZ; block->endptr = ((char *) block) + blksize; @@ -954,76 +895,83 @@ AllocSetAlloc(MemoryContext context, Size size) /* * OK, do the allocation */ - chunk = (AllocChunk) (block->freeptr); - - /* Prepare to initialize the chunk header. */ - VALGRIND_MAKE_MEM_UNDEFINED(chunk, ALLOC_CHUNKHDRSZ); + pointer = (void *) (block->freeptr + SMALL_CHUNK_SIZE); - block->freeptr += (chunk_size + ALLOC_CHUNKHDRSZ); + block->freeptr += (SMALL_CHUNK_SIZE + chunk_size); Assert(block->freeptr <= block->endptr); - chunk->aset = (void *) set; - chunk->size = chunk_size; + #ifdef MEMORY_CONTEXT_CHECKING - chunk->requested_size = size; + GenericChunkHeaderEncode(pointer, block, chunk_size, size, MCTX_ASET_ID); + /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(AllocChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(pointer, size); +#else + GenericChunkHeaderEncode(pointer, block, chunk_size, MCTX_ASET_ID); #endif + #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) pointer, size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) pointer + size, chunk_size - size); - /* Disallow external access to private part of chunk header. */ - VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); + Assert(GetMemoryChunkMethodID(pointer) == MCTX_ASET_ID); - return AllocChunkGetPointer(chunk); + return pointer; } /* * AllocSetFree * Frees allocated memory; memory is removed from the set. */ -static void -AllocSetFree(MemoryContext context, void *pointer) +void +AllocSetFree(void *pointer) { - AllocSet set = (AllocSet) context; - AllocChunk chunk = AllocPointerGetChunk(pointer); + AllocBlock block; + AllocSet set; + Size chunksize; + Size blockoffset; + Size hdrsize; +#ifdef MEMORY_CONTEXT_CHECKING + Size reqsize; + + hdrsize = GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset, &reqsize); +#else + hdrsize = GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset); +#endif - /* Allow access to private part of chunk header. */ - VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); + block = (AllocBlock) ((char *) pointer - blockoffset); + set = block->aset; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunk->size) - if (!sentinel_ok(pointer, chunk->requested_size)) + if (reqsize < chunksize) + if (!sentinel_ok(pointer, reqsize)) elog(WARNING, "detected write past chunk end in %s %p", - set->header.name, chunk); + set->header.name, pointer); #endif - if (chunk->size > set->allocChunkLimit) + if (chunksize > set->allocChunkLimit) { /* * Big chunks are certain to have been allocated as single-chunk * blocks. Just unlink that block and return it to malloc(). */ - AllocBlock block = (AllocBlock) (((char *) chunk) - ALLOC_BLOCKHDRSZ); /* * Try to verify that we have a sane block pointer: it should * reference the correct aset, and freeptr and endptr should point * just past the chunk. */ - if (block->aset != set || - block->freeptr != block->endptr || + if (block->freeptr != block->endptr || block->freeptr != ((char *) block) + - (chunk->size + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) - elog(ERROR, "could not find block containing chunk %p", chunk); + (ALLOC_BLOCKHDRSZ + hdrsize + chunksize)) + elog(ERROR, "could not find block containing pointer %p", pointer); /* OK, remove block from aset's list and free it */ if (block->prev) @@ -1033,7 +981,7 @@ AllocSetFree(MemoryContext context, void *pointer) if (block->next) block->next->prev = block->prev; - context->mem_allocated -= block->endptr - ((char *) block); + set->header.mem_allocated -= block->endptr - ((char *) block); #ifdef CLOBBER_FREED_MEMORY wipe_mem(block, block->freeptr - ((char *) block)); @@ -1043,19 +991,22 @@ AllocSetFree(MemoryContext context, void *pointer) else { /* Normal case, put the chunk into appropriate freelist */ - int fidx = AllocSetFreeIndex(chunk->size); + int fidx = AllocSetFreeIndex(chunksize); - chunk->aset = (void *) set->freelist[fidx]; + /* Use the pointer to store the freelist link */ + *((void **) pointer) = set->freelist[fidx]; #ifdef CLOBBER_FREED_MEMORY - wipe_mem(pointer, chunk->size); + /* Wipe the memory, but not the freelist link we just set above */ + wipe_mem(((char *) pointer) + sizeof(void *), chunksize - sizeof(void *)); #endif #ifdef MEMORY_CONTEXT_CHECKING /* Reset requested_size to 0 in chunks that are on freelist */ - chunk->requested_size = 0; + GenericChunkHeaderEncode(pointer, block, chunksize, 0, MCTX_ASET_ID); #endif - set->freelist[fidx] = chunk; + + set->freelist[fidx] = pointer; } } @@ -1071,24 +1022,32 @@ AllocSetFree(MemoryContext context, void *pointer) * (In principle, we could use VALGRIND_GET_VBITS() to rediscover the old * request size.) */ -static void * -AllocSetRealloc(MemoryContext context, void *pointer, Size size) +void * +AllocSetRealloc(void *pointer, Size size) { - AllocSet set = (AllocSet) context; - AllocChunk chunk = AllocPointerGetChunk(pointer); + AllocBlock block; + AllocSet set; Size oldsize; + Size blockoffset; + Size hdrsize; +#ifdef MEMORY_CONTEXT_CHECKING + Size oldreqsize; - /* Allow access to private part of chunk header. */ - VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); + hdrsize = GenericChunkHeaderDecode(pointer, &oldsize, &blockoffset, &oldreqsize); +#else - oldsize = chunk->size; + hdrsize = GenericChunkHeaderDecode(pointer, &oldsize, &blockoffset); +#endif + + block = (AllocBlock) ((char *) pointer - blockoffset); + set = block->aset; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < oldsize) - if (!sentinel_ok(pointer, chunk->requested_size)) + if (oldreqsize < oldsize) + if (!sentinel_ok(pointer, oldreqsize)) elog(WARNING, "detected write past chunk end in %s %p", - set->header.name, chunk); + set->header.name, pointer); #endif if (oldsize > set->allocChunkLimit) @@ -1098,21 +1057,20 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) * realloc() to make the containing block bigger, or smaller, with * minimum space wastage. */ - AllocBlock block = (AllocBlock) (((char *) chunk) - ALLOC_BLOCKHDRSZ); Size chksize; Size blksize; Size oldblksize; + Size newhdrsize; /* * Try to verify that we have a sane block pointer: it should * reference the correct aset, and freeptr and endptr should point * just past the chunk. */ - if (block->aset != set || - block->freeptr != block->endptr || + if (block->freeptr != block->endptr || block->freeptr != ((char *) block) + - (oldsize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) - elog(ERROR, "could not find block containing chunk %p", chunk); + (ALLOC_BLOCKHDRSZ + hdrsize + oldsize)) + elog(ERROR, "could not find block containing pointer %p", pointer); /* * Even if the new request is less than set->allocChunkLimit, we stick @@ -1123,41 +1081,66 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) chksize = Max(size, set->allocChunkLimit + 1); chksize = MAXALIGN(chksize); + /* Assume big chunk size */ + newhdrsize = GenericChunkHeaderSize(ALLOC_BLOCKHDRSZ + LARGE_CHUNK_SIZE, chksize); + /* Do the realloc */ - blksize = chksize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ; + blksize = ALLOC_BLOCKHDRSZ + newhdrsize + chksize; oldblksize = block->endptr - ((char *) block); - block = (AllocBlock) realloc(block, blksize); - if (block == NULL) + if (newhdrsize == hdrsize) + block = (AllocBlock) realloc(block, blksize); + else { - /* Disallow external access to private part of chunk header. */ - VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return NULL; + /* + * When the size of the chunk header changes, we're unable to + * simply call realloc as the offset between the block and the + * pointer will have changed. For this case we resort to just + * allocating new memory with AllocSetAlloc then copying the old + * memory over before finally freeing the old memory and block + * with AllocSetFree. + */ + void *newPointer = AllocSetAlloc((MemoryContext) set, size); + + if (newPointer == NULL) + return NULL; + + memcpy(newPointer, pointer, Min(oldsize, size)); + + AllocSetFree(pointer); + + return newPointer; } + if (block == NULL) + return NULL; + /* updated separately, not to underflow when (oldblksize > blksize) */ - context->mem_allocated -= oldblksize; - context->mem_allocated += blksize; + set->header.mem_allocated -= oldblksize; + set->header.mem_allocated += blksize; block->freeptr = block->endptr = ((char *) block) + blksize; /* Update pointers since block has likely been moved */ - chunk = (AllocChunk) (((char *) block) + ALLOC_BLOCKHDRSZ); - pointer = AllocChunkGetPointer(chunk); + pointer = (void *) ((char *) block + ALLOC_BLOCKHDRSZ + newhdrsize); if (block->prev) block->prev->next = block; else set->blocks = block; if (block->next) block->next->prev = block; - chunk->size = chksize; + +#ifdef MEMORY_CONTEXT_CHECKING + GenericChunkHeaderEncode(pointer, block, chksize, size, MCTX_ASET_ID); +#else + GenericChunkHeaderEncode(pointer, block, chksize, MCTX_ASET_ID); +#endif #ifdef MEMORY_CONTEXT_CHECKING #ifdef RANDOMIZE_ALLOCATED_MEMORY - /* We can only fill the extra space if we know the prior request */ - if (size > chunk->requested_size) - randomize_mem((char *) pointer + chunk->requested_size, - size - chunk->requested_size); + /* for enlarged chunks, randomize the enlarged portion. */ + if (size > oldreqsize) + randomize_mem(((char *) pointer) + oldreqsize, size - oldreqsize); #endif /* @@ -1166,15 +1149,12 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) * old allocation. */ #ifdef USE_VALGRIND - if (oldsize > chunk->requested_size) - VALGRIND_MAKE_MEM_UNDEFINED((char *) pointer + chunk->requested_size, - oldsize - chunk->requested_size); + if (oldsize > oldreqsize) + VALGRIND_MAKE_MEM_UNDEFINED((char *) pointer + oldreqsize, + oldsize - oldreqsize); #endif - - chunk->requested_size = size; - /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) + if (size < chksize) set_sentinel(pointer, size); #else /* !MEMORY_CONTEXT_CHECKING */ @@ -1189,8 +1169,7 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) /* Ensure any padding bytes are marked NOACCESS. */ VALGRIND_MAKE_MEM_NOACCESS((char *) pointer + size, chksize - size); - /* Disallow external access to private part of chunk header. */ - VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); + Assert(GetMemoryChunkMethodID(pointer) == MCTX_ASET_ID); return pointer; } @@ -1203,24 +1182,19 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) else if (oldsize >= size) { #ifdef MEMORY_CONTEXT_CHECKING - Size oldrequest = chunk->requested_size; - #ifdef RANDOMIZE_ALLOCATED_MEMORY /* We can only fill the extra space if we know the prior request */ - if (size > oldrequest) - randomize_mem((char *) pointer + oldrequest, - size - oldrequest); + if (size > oldreqsize) + randomize_mem((char *) pointer + oldreqsize, + size - oldreqsize); #endif - - chunk->requested_size = size; - /* * If this is an increase, mark any newly-available part UNDEFINED. * Otherwise, mark the obsolete part NOACCESS. */ - if (size > oldrequest) - VALGRIND_MAKE_MEM_UNDEFINED((char *) pointer + oldrequest, - size - oldrequest); + if (size > oldreqsize) + VALGRIND_MAKE_MEM_UNDEFINED((char *) pointer + oldreqsize, + size - oldreqsize); else VALGRIND_MAKE_MEM_NOACCESS((char *) pointer + size, oldsize - size); @@ -1228,6 +1202,9 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) /* set mark to catch clobber of "unused" space */ if (size < oldsize) set_sentinel(pointer, size); + + /* Re-encode the chunk to apply new request size */ + GenericChunkHeaderEncode(pointer, block, oldsize, size, MCTX_ASET_ID); #else /* !MEMORY_CONTEXT_CHECKING */ /* @@ -1239,8 +1216,7 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) VALGRIND_MAKE_MEM_DEFINED(pointer, size); #endif - /* Disallow external access to private part of chunk header. */ - VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); + Assert(GetMemoryChunkMethodID(pointer) == MCTX_ASET_ID); return pointer; } @@ -1264,11 +1240,7 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) /* leave immediately if request was not completed */ if (newPointer == NULL) - { - /* Disallow external access to private part of chunk header. */ - VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); return NULL; - } /* * AllocSetAlloc() may have returned a region that is still NOACCESS. @@ -1279,8 +1251,9 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) * trailing bytes. */ VALGRIND_MAKE_MEM_UNDEFINED(newPointer, size); + #ifdef MEMORY_CONTEXT_CHECKING - oldsize = chunk->requested_size; + oldsize = oldreqsize; #else VALGRIND_MAKE_MEM_DEFINED(pointer, oldsize); #endif @@ -1289,34 +1262,67 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) memcpy(newPointer, pointer, oldsize); /* free old chunk */ - AllocSetFree((MemoryContext) set, pointer); + AllocSetFree(pointer); + + Assert(GetMemoryChunkMethodID(newPointer) == MCTX_ASET_ID); return newPointer; } } +/* + * AllocSetGetChunkContext + * Return the MemoryContext that 'pointer' belongs to. + */ +MemoryContext +AllocSetGetChunkContext(void *pointer) +{ + AllocBlock block; + AllocSet set; + Size chunksize; + Size blockoffset; +#ifdef MEMORY_CONTEXT_CHECKING + Size reqsize; + + GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset, &reqsize); +#else + GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset); +#endif + + block = (AllocBlock) ((char *) pointer - blockoffset); + + set = block->aset; + + return &set->header; +} + /* * AllocSetGetChunkSpace * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -AllocSetGetChunkSpace(MemoryContext context, void *pointer) +Size +AllocSetGetChunkSpace(void *pointer) { - AllocChunk chunk = AllocPointerGetChunk(pointer); - Size result; + Size chunksize; + Size blockoffset; + Size hdrsize; +#ifdef MEMORY_CONTEXT_CHECKING + Size reqsize; - VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - result = chunk->size + ALLOC_CHUNKHDRSZ; - VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return result; + hdrsize = GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset, &reqsize); +#else + hdrsize = GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset); +#endif + + return hdrsize + chunksize; } /* * AllocSetIsEmpty * Is an allocset empty of any allocated space? */ -static bool +bool AllocSetIsEmpty(MemoryContext context) { /* @@ -1339,7 +1345,7 @@ AllocSetIsEmpty(MemoryContext context) * totals: if not NULL, add stats about this context into *totals. * print_to_stderr: print stats to stderr if true, elog otherwise. */ -static void +void AllocSetStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr) @@ -1363,13 +1369,19 @@ AllocSetStats(MemoryContext context, } for (fidx = 0; fidx < ALLOCSET_NUM_FREELISTS; fidx++) { - AllocChunk chunk; + void *pointer = set->freelist[fidx]; + Size chunk_size = (1 << ALLOC_MINBITS) << fidx; - for (chunk = set->freelist[fidx]; chunk != NULL; - chunk = (AllocChunk) chunk->aset) + while (pointer != NULL) { freechunks++; - freespace += chunk->size + ALLOC_CHUNKHDRSZ; + freespace += chunk_size + SMALL_CHUNK_SIZE; + + /* + * Set pointer to the next freelist item which is stored in the + * pointed to memory. + */ + pointer = *((void **) pointer); } } @@ -1404,7 +1416,7 @@ AllocSetStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void AllocSetCheck(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -1421,6 +1433,7 @@ AllocSetCheck(MemoryContext context) long blk_used = block->freeptr - bpoz; long blk_data = 0; long nchunks = 0; + Size expected_hdrsize; if (set->keeper == block) total_allocated += block->endptr - ((char *) set); @@ -1447,69 +1460,64 @@ AllocSetCheck(MemoryContext context) elog(WARNING, "problem in alloc set %s: corrupt header in block %p", name, block); + if (block->large_chunk) + expected_hdrsize = LARGE_CHUNK_SIZE; + else + expected_hdrsize = SMALL_CHUNK_SIZE; + /* * Chunk walker */ while (bpoz < block->freeptr) { - AllocChunk chunk = (AllocChunk) bpoz; - Size chsize, - dsize; + void *pointer; + Size chsize; + Size blkoff; + Size hdrsize; + Size reqsize; - /* Allow access to private part of chunk header. */ - VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - - chsize = chunk->size; /* aligned chunk size */ - dsize = chunk->requested_size; /* real data */ + pointer = bpoz + expected_hdrsize; + hdrsize = GenericChunkHeaderDecode(pointer, &chsize, &blkoff, &reqsize); /* * Check chunk size */ - if (dsize > chsize) - elog(WARNING, "problem in alloc set %s: req size > alloc size for chunk %p in block %p", - name, chunk, block); + if (expected_hdrsize != hdrsize) + elog(WARNING, "problem in alloc set %s: expected chunk header size is %zu but actual size is %zu", + name, expected_hdrsize, hdrsize); + if (reqsize > chsize) + elog(WARNING, "problem in alloc set %s: req size > alloc size for pointer %p in block %p", + name, pointer, block); if (chsize < (1 << ALLOC_MINBITS)) - elog(WARNING, "problem in alloc set %s: bad size %zu for chunk %p in block %p", - name, chsize, chunk, block); + elog(WARNING, "problem in alloc set %s: bad size %zu for pointer %p in block %p", + name, chsize, pointer, block); /* single-chunk block? */ if (chsize > set->allocChunkLimit && - chsize + ALLOC_CHUNKHDRSZ != blk_used) - elog(WARNING, "problem in alloc set %s: bad single-chunk %p in block %p", - name, chunk, block); + chsize + expected_hdrsize != blk_used) + elog(WARNING, "problem in alloc set %s: bad single-chunk pointer %p in block %p", + name, pointer, block); - /* - * If chunk is allocated, check for correct aset pointer. (If it's - * free, the aset is the freelist pointer, which we can't check as - * easily...) Note this is an incomplete test, since palloc(0) - * produces an allocated chunk with requested_size == 0. - */ - if (dsize > 0 && chunk->aset != (void *) set) - elog(WARNING, "problem in alloc set %s: bogus aset link in block %p, chunk %p", - name, block, chunk); + /* Check the block offset correctly matches this block */ + if ((AllocBlock) ((char *) pointer - blkoff) != block) + elog(WARNING, "problem in alloc set %s: bad block offset for pointer %p in block %p", + name, pointer, block); /* * Check for overwrite of padding space in an allocated chunk. */ - if (chunk->aset == (void *) set && dsize < chsize && - !sentinel_ok(chunk, ALLOC_CHUNKHDRSZ + dsize)) - elog(WARNING, "problem in alloc set %s: detected write past chunk end in block %p, chunk %p", - name, block, chunk); - - /* - * If chunk is allocated, disallow external access to private part - * of chunk header. - */ - if (chunk->aset == (void *) set) - VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); + if (reqsize > 0 && reqsize < chsize && + !sentinel_ok(pointer, reqsize)) + elog(WARNING, "problem in alloc set %s: detected write past chunk end in block %p, pointer %p", + name, block, pointer); blk_data += chsize; nchunks++; - bpoz += ALLOC_CHUNKHDRSZ + chsize; + bpoz += expected_hdrsize + chsize; } - if ((blk_data + (nchunks * ALLOC_CHUNKHDRSZ)) != blk_used) + if (bpoz != block->freeptr) elog(WARNING, "problem in alloc set %s: found inconsistent memory block %p", name, block); } diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index e530e272e0..3a4e7588c6 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -39,15 +39,15 @@ #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_generichdr.h" +#include "utils/memutils_internal.h" #define Generation_BLOCKHDRSZ MAXALIGN(sizeof(GenerationBlock)) -#define Generation_CHUNKHDRSZ sizeof(GenerationChunk) #define Generation_CHUNK_FRACTION 8 typedef struct GenerationBlock GenerationBlock; /* forward reference */ -typedef struct GenerationChunk GenerationChunk; typedef void *GenerationPointer; @@ -89,112 +89,29 @@ typedef struct GenerationContext struct GenerationBlock { dlist_node node; /* doubly-linked list of blocks */ + GenerationContext *context; Size blksize; /* allocated size of this block */ int nchunks; /* number of chunks in the block */ int nfree; /* number of free chunks */ + bool large_chunk; /* true if the only chunk is a large chunk */ char *freeptr; /* start of free space in this block */ char *endptr; /* end of space in this block */ }; -/* - * GenerationChunk - * The prefix of each piece of memory in a GenerationBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "context" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). We simplify matters for this - * module by requiring sizeof(GenerationChunk) to be maxaligned, and then - * we can ensure things work by adding any required alignment padding before - * the pointer fields. There is a static assertion below that the alignment - * is done correctly. - */ -struct GenerationChunk -{ - /* size is always the size of the usable space in the chunk */ - Size size; -#ifdef MEMORY_CONTEXT_CHECKING - /* when debugging memory usage, also store actual requested size */ - /* this is zero in a free chunk */ - Size requested_size; - -#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T * 2 + SIZEOF_VOID_P * 2) -#else -#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P * 2) -#endif /* MEMORY_CONTEXT_CHECKING */ - - /* ensure proper alignment by adding padding if needed */ -#if (GENERATIONCHUNK_RAWSIZE % MAXIMUM_ALIGNOF) != 0 - char padding[MAXIMUM_ALIGNOF - GENERATIONCHUNK_RAWSIZE % MAXIMUM_ALIGNOF]; -#endif - - GenerationBlock *block; /* block owning this chunk */ - GenerationContext *context; /* owning context, or NULL if freed chunk */ - /* there must not be any padding to reach a MAXALIGN boundary here! */ -}; - -/* - * Only the "context" field should be accessed outside this module. - * We keep the rest of an allocated chunk's header marked NOACCESS when using - * valgrind. But note that freed chunk headers are kept accessible, for - * simplicity. - */ -#define GENERATIONCHUNK_PRIVATE_LEN offsetof(GenerationChunk, context) - /* * GenerationIsValid * True iff set is valid allocation set. */ #define GenerationIsValid(set) PointerIsValid(set) -#define GenerationPointerGetChunk(ptr) \ - ((GenerationChunk *)(((char *)(ptr)) - Generation_CHUNKHDRSZ)) -#define GenerationChunkGetPointer(chk) \ - ((GenerationPointer *)(((char *)(chk)) + Generation_CHUNKHDRSZ)) - /* Inlined helper functions */ -static inline void GenerationBlockInit(GenerationBlock *block, Size blksize); +static inline void GenerationBlockInit(GenerationContext *context, GenerationBlock *block, Size blksize); static inline bool GenerationBlockIsEmpty(GenerationBlock *block); static inline void GenerationBlockMarkEmpty(GenerationBlock *block); static inline Size GenerationBlockFreeBytes(GenerationBlock *block); static inline void GenerationBlockFree(GenerationContext *set, GenerationBlock *block); -/* - * These functions implement the MemoryContext API for Generation contexts. - */ -static void *GenerationAlloc(MemoryContext context, Size size); -static void GenerationFree(MemoryContext context, void *pointer); -static void *GenerationRealloc(MemoryContext context, void *pointer, Size size); -static void GenerationReset(MemoryContext context); -static void GenerationDelete(MemoryContext context); -static Size GenerationGetChunkSpace(MemoryContext context, void *pointer); -static bool GenerationIsEmpty(MemoryContext context); -static void GenerationStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); - -#ifdef MEMORY_CONTEXT_CHECKING -static void GenerationCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for Generation contexts. - */ -static const MemoryContextMethods GenerationMethods = { - GenerationAlloc, - GenerationFree, - GenerationRealloc, - GenerationReset, - GenerationDelete, - GenerationGetChunkSpace, - GenerationIsEmpty, - GenerationStats -#ifdef MEMORY_CONTEXT_CHECKING - ,GenerationCheck -#endif -}; - /* * Public routines @@ -223,13 +140,6 @@ GenerationContextCreate(MemoryContext parent, GenerationContext *set; GenerationBlock *block; - /* Assert we padded GenerationChunk properly */ - StaticAssertStmt(Generation_CHUNKHDRSZ == MAXALIGN(Generation_CHUNKHDRSZ), - "sizeof(GenerationChunk) is not maxaligned"); - StaticAssertStmt(offsetof(GenerationChunk, context) + sizeof(MemoryContext) == - Generation_CHUNKHDRSZ, - "padding calculation in GenerationChunk is wrong"); - /* * First, validate allocation parameters. Asserts seem sufficient because * nobody varies their parameters at runtime. We somewhat arbitrarily @@ -244,10 +154,11 @@ GenerationContextCreate(MemoryContext parent, (minContextSize == MAXALIGN(minContextSize) && minContextSize >= 1024 && minContextSize <= maxBlockSize)); + Assert(maxBlockSize <= SMALL_CHUNK_LIMIT); /* Determine size of initial block */ allocSize = MAXALIGN(sizeof(GenerationContext)) + - Generation_BLOCKHDRSZ + Generation_CHUNKHDRSZ; + Generation_BLOCKHDRSZ + LARGE_CHUNK_SIZE; if (minContextSize != 0) allocSize = Max(allocSize, minContextSize); else @@ -278,7 +189,7 @@ GenerationContextCreate(MemoryContext parent, block = (GenerationBlock *) (((char *) set) + MAXALIGN(sizeof(GenerationContext))); /* determine the block size and initialize it */ firstBlockSize = allocSize - MAXALIGN(sizeof(GenerationContext)); - GenerationBlockInit(block, firstBlockSize); + GenerationBlockInit(set, block, firstBlockSize); /* add it to the doubly-linked list of blocks */ dlist_push_head(&set->blocks, &block->node); @@ -302,15 +213,15 @@ GenerationContextCreate(MemoryContext parent, * * Follows similar ideas as AllocSet, see aset.c for details ... */ - set->allocChunkLimit = maxBlockSize; - while ((Size) (set->allocChunkLimit + Generation_CHUNKHDRSZ) > + set->allocChunkLimit = Min(maxBlockSize, SMALL_CHUNK_LIMIT); + while ((Size) (set->allocChunkLimit + SMALL_CHUNK_SIZE) > (Size) ((Size) (maxBlockSize - Generation_BLOCKHDRSZ) / Generation_CHUNK_FRACTION)) set->allocChunkLimit >>= 1; /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) set, T_GenerationContext, - &GenerationMethods, + MCTX_GENERATION_ID, parent, name); @@ -326,7 +237,7 @@ GenerationContextCreate(MemoryContext parent, * The code simply frees all the blocks in the context - we don't keep any * keeper blocks or anything like that. */ -static void +void GenerationReset(MemoryContext context) { GenerationContext *set = (GenerationContext *) context; @@ -371,7 +282,7 @@ GenerationReset(MemoryContext context) * GenerationDelete * Free all memory which is allocated in the given context. */ -static void +void GenerationDelete(MemoryContext context) { /* Reset to release all releasable GenerationBlocks */ @@ -393,19 +304,23 @@ GenerationDelete(MemoryContext context) * is marked, as mcxt.c will set it to UNDEFINED. In some paths we will * return space that is marked NOACCESS - GenerationRealloc has to beware! */ -static void * +void * GenerationAlloc(MemoryContext context, Size size) { GenerationContext *set = (GenerationContext *) context; GenerationBlock *block; - GenerationChunk *chunk; Size chunk_size = MAXALIGN(size); - Size required_size = chunk_size + Generation_CHUNKHDRSZ; + Size genhdrsize; + Size required_size; + void *pointer; /* is it an over-sized chunk? if yes, allocate special block */ if (chunk_size > set->allocChunkLimit) { - Size blksize = required_size + Generation_BLOCKHDRSZ; + Size blksize; + + genhdrsize = GenericChunkHeaderSize(Generation_BLOCKHDRSZ + LARGE_CHUNK_SIZE, chunk_size); + blksize = Generation_BLOCKHDRSZ + genhdrsize + chunk_size; block = (GenerationBlock *) malloc(blksize); if (block == NULL) @@ -414,24 +329,27 @@ GenerationAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; /* block with a single (used) chunk */ + block->context = set; block->blksize = blksize; block->nchunks = 1; block->nfree = 0; + block->large_chunk = (genhdrsize == LARGE_CHUNK_SIZE); /* the block is completely full */ block->freeptr = block->endptr = ((char *) block) + blksize; - chunk = (GenerationChunk *) (((char *) block) + Generation_BLOCKHDRSZ); - chunk->block = block; - chunk->context = set; - chunk->size = chunk_size; + pointer = (void *) ((char *) block + Generation_BLOCKHDRSZ + genhdrsize); #ifdef MEMORY_CONTEXT_CHECKING - chunk->requested_size = size; + GenericChunkHeaderEncode(pointer, block, chunk_size, size, MCTX_GENERATION_ID); + /* set mark to catch clobber of "unused" space */ if (size < chunk_size) - set_sentinel(GenerationChunkGetPointer(chunk), size); + set_sentinel(pointer, size); +#else + GenericChunkHeaderEncode(pointer, block, chunk_size, MCTX_GENERATION_ID); #endif + #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ randomize_mem((char *) GenerationChunkGetPointer(chunk), size); @@ -441,13 +359,10 @@ GenerationAlloc(MemoryContext context, Size size) dlist_push_head(&set->blocks, &block->node); /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) GenerationChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) pointer + size, chunk_size - size); - /* Disallow external access to private part of chunk header. */ - VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - - return GenerationChunkGetPointer(chunk); + return pointer; } /* @@ -466,6 +381,7 @@ GenerationAlloc(MemoryContext context, Size size) * that would compound over time. */ block = set->block; + required_size = SMALL_CHUNK_SIZE + chunk_size; if (block == NULL || GenerationBlockFreeBytes(block) < required_size) @@ -492,6 +408,7 @@ GenerationAlloc(MemoryContext context, Size size) } else { + /* * The first such block has size initBlockSize, and we double the * space in each succeeding block, but not more than maxBlockSize. @@ -501,12 +418,9 @@ GenerationAlloc(MemoryContext context, Size size) if (set->nextBlockSize > set->maxBlockSize) set->nextBlockSize = set->maxBlockSize; - /* we'll need a block hdr too, so add that to the required size */ - required_size += Generation_BLOCKHDRSZ; - /* round the size up to the next power of 2 */ - if (blksize < required_size) - blksize = pg_nextpower2_size_t(required_size); + if (blksize < required_size + Generation_BLOCKHDRSZ) + blksize = pg_nextpower2_size_t(required_size + Generation_BLOCKHDRSZ); block = (GenerationBlock *) malloc(blksize); @@ -516,7 +430,7 @@ GenerationAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; /* initialize the new block */ - GenerationBlockInit(block, blksize); + GenerationBlockInit(set, block, blksize); /* add it to the doubly-linked list of blocks */ dlist_push_head(&set->blocks, &block->node); @@ -531,41 +445,34 @@ GenerationAlloc(MemoryContext context, Size size) /* we're supposed to have a block with enough free space now */ Assert(block != NULL); - Assert((block->endptr - block->freeptr) >= Generation_CHUNKHDRSZ + chunk_size); - - chunk = (GenerationChunk *) block->freeptr; + Assert((block->endptr - block->freeptr) >= required_size); - /* Prepare to initialize the chunk header. */ - VALGRIND_MAKE_MEM_UNDEFINED(chunk, Generation_CHUNKHDRSZ); + pointer = (void *) (block->freeptr + SMALL_CHUNK_SIZE); block->nchunks += 1; - block->freeptr += (Generation_CHUNKHDRSZ + chunk_size); + block->freeptr += required_size; Assert(block->freeptr <= block->endptr); - chunk->block = block; - chunk->context = set; - chunk->size = chunk_size; - #ifdef MEMORY_CONTEXT_CHECKING - chunk->requested_size = size; + GenericChunkHeaderEncode(pointer, block, chunk_size, size, MCTX_GENERATION_ID); /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(GenerationChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(pointer, size); +#else + GenericChunkHeaderEncode(pointer, block, chunk_size, MCTX_GENERATION_ID); #endif + #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) GenerationChunkGetPointer(chunk), size); + randomize_mem(pointer, size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) GenerationChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) pointer + size, chunk_size - size); - /* Disallow external access to private part of chunk header. */ - VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - - return GenerationChunkGetPointer(chunk); + return pointer; } /* @@ -574,12 +481,14 @@ GenerationAlloc(MemoryContext context, Size size) * mem_allocated field. */ static inline void -GenerationBlockInit(GenerationBlock *block, Size blksize) +GenerationBlockInit(GenerationContext *context, GenerationBlock *block, Size blksize) { + block->context = context; block->blksize = blksize; block->nchunks = 0; block->nfree = 0; + block->large_chunk = false; block->freeptr = ((char *) block) + Generation_BLOCKHDRSZ; block->endptr = ((char *) block) + blksize; @@ -661,36 +570,41 @@ GenerationBlockFree(GenerationContext *set, GenerationBlock *block) * Update number of chunks in the block, and if all chunks in the block * are now free then discard the block. */ -static void -GenerationFree(MemoryContext context, void *pointer) +void +GenerationFree(void *pointer) { - GenerationContext *set = (GenerationContext *) context; - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); GenerationBlock *block; + GenerationContext *set; + Size chunksize; + Size blockoffset; +#ifdef MEMORY_CONTEXT_CHECKING + Size reqsize; + + GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset, &reqsize); + +#else + GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset); +#endif - /* Allow access to private part of chunk header. */ - VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); + block = (GenerationBlock *) (((char *) pointer) - blockoffset); - block = chunk->block; + set = block->context; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunk->size) - if (!sentinel_ok(pointer, chunk->requested_size)) + if (reqsize < chunksize) + if (!sentinel_ok(pointer, reqsize)) elog(WARNING, "detected write past chunk end in %s %p", - ((MemoryContext) set)->name, chunk); + ((MemoryContext) set)->name, pointer); #endif #ifdef CLOBBER_FREED_MEMORY - wipe_mem(pointer, chunk->size); + wipe_mem(pointer, chunksize); #endif - /* Reset context to NULL in freed chunks */ - chunk->context = NULL; - #ifdef MEMORY_CONTEXT_CHECKING /* Reset requested_size to 0 in freed chunks */ - chunk->requested_size = 0; + GenericChunkHeaderEncode(pointer, (void *) block, chunksize, 0, MCTX_GENERATION_ID); #endif block->nfree += 1; @@ -732,7 +646,7 @@ GenerationFree(MemoryContext context, void *pointer) */ dlist_delete(&block->node); - context->mem_allocated -= block->blksize; + set->header.mem_allocated -= block->blksize; free(block); } @@ -742,25 +656,32 @@ GenerationFree(MemoryContext context, void *pointer) * and discard the old one. The only exception is when the new size fits * into the old chunk - in that case we just update chunk header. */ -static void * -GenerationRealloc(MemoryContext context, void *pointer, Size size) +void * +GenerationRealloc(void *pointer, Size size) { - GenerationContext *set = (GenerationContext *) context; - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); + GenerationBlock *block; + GenerationContext *set; GenerationPointer newPointer; Size oldsize; + Size blockoffset; +#ifdef MEMORY_CONTEXT_CHECKING + Size oldreqsize; - /* Allow access to private part of chunk header. */ - VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); + GenericChunkHeaderDecode(pointer, &oldsize, &blockoffset, &oldreqsize); - oldsize = chunk->size; +#else + GenericChunkHeaderDecode(pointer, &oldsize, &blockoffset); +#endif + + block = (GenerationBlock *) (((char *) pointer) - blockoffset); + set = block->context; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < oldsize) - if (!sentinel_ok(pointer, chunk->requested_size)) + if (oldreqsize < oldsize) + if (!sentinel_ok(pointer, oldreqsize)) elog(WARNING, "detected write past chunk end in %s %p", - ((MemoryContext) set)->name, chunk); + ((MemoryContext) set)->name, pointer); #endif /* @@ -776,24 +697,20 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) if (oldsize >= size) { #ifdef MEMORY_CONTEXT_CHECKING - Size oldrequest = chunk->requested_size; #ifdef RANDOMIZE_ALLOCATED_MEMORY /* We can only fill the extra space if we know the prior request */ - if (size > oldrequest) - randomize_mem((char *) pointer + oldrequest, - size - oldrequest); + if (size > oldreqsize) + randomize_mem((char *) pointer + oldreqsize, + size - oldreqsize); #endif - - chunk->requested_size = size; - /* * If this is an increase, mark any newly-available part UNDEFINED. * Otherwise, mark the obsolete part NOACCESS. */ - if (size > oldrequest) - VALGRIND_MAKE_MEM_UNDEFINED((char *) pointer + oldrequest, - size - oldrequest); + if (size > oldreqsize) + VALGRIND_MAKE_MEM_UNDEFINED((char *) pointer + oldreqsize, + size - oldreqsize); else VALGRIND_MAKE_MEM_NOACCESS((char *) pointer + size, oldsize - size); @@ -801,6 +718,9 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) /* set mark to catch clobber of "unused" space */ if (size < oldsize) set_sentinel(pointer, size); + + /* Re-encode the chunk to apply new request size */ + GenericChunkHeaderEncode(pointer, block, oldsize, size, MCTX_GENERATION_ID); #else /* !MEMORY_CONTEXT_CHECKING */ /* @@ -812,9 +732,6 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) VALGRIND_MAKE_MEM_DEFINED(pointer, size); #endif - /* Disallow external access to private part of chunk header. */ - VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return pointer; } @@ -824,8 +741,6 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) /* leave immediately if request was not completed */ if (newPointer == NULL) { - /* Disallow external access to private part of chunk header. */ - VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); return NULL; } @@ -839,7 +754,7 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) */ VALGRIND_MAKE_MEM_UNDEFINED(newPointer, size); #ifdef MEMORY_CONTEXT_CHECKING - oldsize = chunk->requested_size; + oldsize = oldreqsize; #else VALGRIND_MAKE_MEM_DEFINED(pointer, oldsize); #endif @@ -848,7 +763,7 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) memcpy(newPointer, pointer, oldsize); /* free old chunk */ - GenerationFree((MemoryContext) set, pointer); + GenerationFree(pointer); return newPointer; } @@ -858,23 +773,52 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -GenerationGetChunkSpace(MemoryContext context, void *pointer) +MemoryContext +GenerationGetChunkContext(void *pointer) +{ + GenerationBlock *block; + Size chunksize; + Size blockoffset; +#ifdef MEMORY_CONTEXT_CHECKING + Size reqsize; + + GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset, &reqsize); +#else + GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset); +#endif + + block = (GenerationBlock *) (((char *) pointer) - blockoffset); + + return &block->context->header; +} + +/* + * GenerationGetChunkSpace + * Given a currently-allocated chunk, determine the total space + * it occupies (including all memory-allocation overhead). + */ +Size +GenerationGetChunkSpace(void *pointer) { - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); - Size result; + Size chunksize; + Size blockoffset; + Size hdrsize; +#ifdef MEMORY_CONTEXT_CHECKING + Size reqsize; - VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - result = chunk->size + Generation_CHUNKHDRSZ; - VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return result; + hdrsize = GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset, &reqsize); +#else + hdrsize = GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset); +#endif + + return hdrsize + chunksize; } /* * GenerationIsEmpty * Is a GenerationContext empty of any allocated space? */ -static bool +bool GenerationIsEmpty(MemoryContext context) { GenerationContext *set = (GenerationContext *) context; @@ -903,7 +847,7 @@ GenerationIsEmpty(MemoryContext context) * XXX freespace only accounts for empty space at the end of the block, not * space of freed chunks (which is unknown). */ -static void +void GenerationStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr) @@ -961,7 +905,7 @@ GenerationStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void GenerationCheck(MemoryContext context) { GenerationContext *gen = (GenerationContext *) context; @@ -973,6 +917,7 @@ GenerationCheck(MemoryContext context) dlist_foreach(iter, &gen->blocks) { GenerationBlock *block = dlist_container(GenerationBlock, node, iter.cur); + Size expected_hdrsize; int nfree, nchunks; char *ptr; @@ -987,6 +932,16 @@ GenerationCheck(MemoryContext context) elog(WARNING, "problem in Generation %s: number of free chunks %d in block %p exceeds %d allocated", name, block->nfree, block, block->nchunks); + /* check block belongs to the correct context */ + if (block->context != gen) + elog(WARNING, "problem in Generation %s: bogus context link in block %p", + name, block); + + if (block->large_chunk) + expected_hdrsize = LARGE_CHUNK_SIZE; + else + expected_hdrsize = SMALL_CHUNK_SIZE; + /* Now walk through the chunks and count them. */ nfree = 0; nchunks = 0; @@ -994,55 +949,43 @@ GenerationCheck(MemoryContext context) while (ptr < block->freeptr) { - GenerationChunk *chunk = (GenerationChunk *) ptr; + void *pointer = ptr + expected_hdrsize; + Size chsize; + Size blkoff; + Size hdrsize; + Size reqsize; + - /* Allow access to private part of chunk header. */ - VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); + hdrsize = GenericChunkHeaderDecode(pointer, &chsize, &blkoff, &reqsize); /* move to the next chunk */ - ptr += (chunk->size + Generation_CHUNKHDRSZ); + ptr += hdrsize + chsize; nchunks += 1; - /* chunks have both block and context pointers, so check both */ - if (chunk->block != block) - elog(WARNING, "problem in Generation %s: bogus block link in block %p, chunk %p", - name, block, chunk); + if (expected_hdrsize != hdrsize) + elog(WARNING, "problem in Generation %s: expected chunk header size is %zu but actual size is %zu", + name, expected_hdrsize, hdrsize); - /* - * Check for valid context pointer. Note this is an incomplete - * test, since palloc(0) produces an allocated chunk with - * requested_size == 0. - */ - if ((chunk->requested_size > 0 && chunk->context != gen) || - (chunk->context != gen && chunk->context != NULL)) - elog(WARNING, "problem in Generation %s: bogus context link in block %p, chunk %p", - name, block, chunk); + /* Check the block offset correctly matches this block */ + if ((GenerationBlock *) ((char *) pointer - blkoff) != block) + elog(WARNING, "problem in Generation %s: bogus block link in block %p, pointer %p", + name, block, pointer); /* now make sure the chunk size is correct */ - if (chunk->size < chunk->requested_size || - chunk->size != MAXALIGN(chunk->size)) - elog(WARNING, "problem in Generation %s: bogus chunk size in block %p, chunk %p", - name, block, chunk); + if (chsize < reqsize || chsize != MAXALIGN(chsize)) + elog(WARNING, "problem in Generation %s: bogus chunk size in block %p, pointer %p", + name, block, pointer); - /* is chunk allocated? */ - if (chunk->context != NULL) + if (reqsize > 0) { - /* check sentinel, but only in allocated blocks */ - if (chunk->requested_size < chunk->size && - !sentinel_ok(chunk, Generation_CHUNKHDRSZ + chunk->requested_size)) - elog(WARNING, "problem in Generation %s: detected write past chunk end in block %p, chunk %p", - name, block, chunk); + /* check sentinel */ + if (reqsize < chsize && !sentinel_ok(pointer, reqsize)) + elog(WARNING, "problem in Generation %s: detected write past chunk end in block %p, pointer %p", + name, block, pointer); } else nfree += 1; - - /* - * If chunk is allocated, disallow external access to private part - * of chunk header. - */ - if (chunk->context != NULL) - VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); } /* diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index e12be1b9bd..f7cd413eea 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -29,12 +29,60 @@ #include "utils/fmgrprotos.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_internal.h" /***************************************************************************** * GLOBAL MEMORY * *****************************************************************************/ +static const MemoryContextMethods mcxt_methods[] = { + [MCTX_ASET_ID] = { + AllocSetAlloc, + AllocSetFree, + AllocSetRealloc, + AllocSetReset, + AllocSetDelete, + AllocSetGetChunkContext, + AllocSetGetChunkSpace, + AllocSetIsEmpty, + AllocSetStats +#ifdef MEMORY_CONTEXT_CHECKING + ,AllocSetCheck +#endif + }, + + [MCTX_GENERATION_ID] = { + GenerationAlloc, + GenerationFree, + GenerationRealloc, + GenerationReset, + GenerationDelete, + GenerationGetChunkContext, + GenerationGetChunkSpace, + GenerationIsEmpty, + GenerationStats +#ifdef MEMORY_CONTEXT_CHECKING + ,GenerationCheck +#endif + }, + + [MCTX_SLAB_ID] = { + SlabAlloc, + SlabFree, + SlabRealloc, + SlabReset, + SlabDelete, + SlabGetChunkContext, + SlabGetChunkSpace, + SlabIsEmpty, + SlabStats +#ifdef MEMORY_CONTEXT_CHECKING + ,SlabCheck +#endif + }, +}; + /* * CurrentMemoryContext * Default memory context for allocations. @@ -74,6 +122,9 @@ static void MemoryContextStatsPrint(MemoryContext context, void *passthru, Assert(CritSectionCount == 0 || (context)->allowInCritSection) +#define MCXT_METHOD(pointer, method) mcxt_methods[GetMemoryChunkMethodID(pointer)].method + + /***************************************************************************** * EXPORTED ROUTINES * *****************************************************************************/ @@ -422,6 +473,17 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) context->allowInCritSection = allow; } +/* + * GetMemoryChunkContext + * Given a currently-allocated chunk, determine the MemoryContext that + * the chunk belongs to. + */ +MemoryContext +GetMemoryChunkContext(void *pointer) +{ + return MCXT_METHOD(pointer, get_chunk_context)(pointer); +} + /* * GetMemoryChunkSpace * Given a currently-allocated chunk, determine the total space @@ -433,9 +495,7 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) Size GetMemoryChunkSpace(void *pointer) { - MemoryContext context = GetMemoryChunkContext(pointer); - - return context->methods->get_chunk_space(context, pointer); + return MCXT_METHOD(pointer, get_chunk_space)(pointer); } /* @@ -814,7 +874,7 @@ MemoryContextContains(MemoryContext context, void *pointer) void MemoryContextCreate(MemoryContext node, NodeTag tag, - const MemoryContextMethods *methods, + MemoryContextMethodID method_id, MemoryContext parent, const char *name) { @@ -824,7 +884,7 @@ MemoryContextCreate(MemoryContext node, /* Initialize all standard fields of memory context header */ node->type = tag; node->isReset = true; - node->methods = methods; + node->methods = &mcxt_methods[method_id]; node->parent = parent; node->firstchild = NULL; node->mem_allocated = 0; @@ -1174,10 +1234,8 @@ palloc_extended(Size size, int flags) void pfree(void *pointer) { - MemoryContext context = GetMemoryChunkContext(pointer); - - context->methods->free_p(context, pointer); - VALGRIND_MEMPOOL_FREE(context, pointer); + MCXT_METHOD(pointer, free_p)(pointer); + VALGRIND_MEMPOOL_FREE(GetMemoryChunkContext(pointer), pointer); } /* @@ -1187,9 +1245,12 @@ pfree(void *pointer) void * repalloc(void *pointer, Size size) { - MemoryContext context = GetMemoryChunkContext(pointer); void *ret; +#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND) + MemoryContext context = GetMemoryChunkContext(pointer); +#endif + if (!AllocSizeIsValid(size)) elog(ERROR, "invalid memory alloc request size %zu", size); @@ -1198,9 +1259,11 @@ repalloc(void *pointer, Size size) /* isReset must be false already */ Assert(!context->isReset); - ret = context->methods->realloc(context, pointer, size); + ret = MCXT_METHOD(pointer, realloc)(pointer, size); if (unlikely(ret == NULL)) { + MemoryContext context = GetMemoryChunkContext(pointer); + MemoryContextStats(TopMemoryContext); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), @@ -1257,9 +1320,12 @@ MemoryContextAllocHuge(MemoryContext context, Size size) void * repalloc_huge(void *pointer, Size size) { - MemoryContext context = GetMemoryChunkContext(pointer); void *ret; +#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND) + MemoryContext context = GetMemoryChunkContext(pointer); +#endif + if (!AllocHugeSizeIsValid(size)) elog(ERROR, "invalid memory alloc request size %zu", size); @@ -1268,9 +1334,11 @@ repalloc_huge(void *pointer, Size size) /* isReset must be false already */ Assert(!context->isReset); - ret = context->methods->realloc(context, pointer, size); + ret = MCXT_METHOD(pointer, realloc)(pointer, size); if (unlikely(ret == NULL)) { + MemoryContext context = GetMemoryChunkContext(pointer); + MemoryContextStats(TopMemoryContext); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), diff --git a/src/backend/utils/mmgr/slab.c b/src/backend/utils/mmgr/slab.c index 67d97b22e5..a1d9326c66 100644 --- a/src/backend/utils/mmgr/slab.c +++ b/src/backend/utils/mmgr/slab.c @@ -55,6 +55,8 @@ #include "lib/ilist.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_generichdr.h" +#include "utils/memutils_internal.h" /* * SlabContext is a specialized implementation of MemoryContext. @@ -90,74 +92,15 @@ typedef struct SlabBlock dlist_node node; /* doubly-linked list */ int nfree; /* number of free chunks */ int firstFreeChunk; /* index of the first free chunk in the block */ -} SlabBlock; - -/* - * SlabChunk - * The prefix of each piece of memory in a SlabBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "slab" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). Since we support no machines on - * which MAXALIGN is more than twice sizeof(void *), this happens without any - * special hacking in this struct declaration. But there is a static - * assertion below that the alignment is done correctly. - */ -typedef struct SlabChunk -{ - SlabBlock *block; /* block owning this chunk */ SlabContext *slab; /* owning context */ - /* there must not be any padding to reach a MAXALIGN boundary here! */ -} SlabChunk; - - -#define SlabPointerGetChunk(ptr) \ - ((SlabChunk *)(((char *)(ptr)) - sizeof(SlabChunk))) -#define SlabChunkGetPointer(chk) \ - ((void *)(((char *)(chk)) + sizeof(SlabChunk))) -#define SlabBlockGetChunk(slab, block, idx) \ - ((SlabChunk *) ((char *) (block) + sizeof(SlabBlock) \ - + (idx * slab->fullChunkSize))) -#define SlabBlockStart(block) \ - ((char *) block + sizeof(SlabBlock)) -#define SlabChunkIndex(slab, block, chunk) \ - (((char *) chunk - SlabBlockStart(block)) / slab->fullChunkSize) - -/* - * These functions implement the MemoryContext API for Slab contexts. - */ -static void *SlabAlloc(MemoryContext context, Size size); -static void SlabFree(MemoryContext context, void *pointer); -static void *SlabRealloc(MemoryContext context, void *pointer, Size size); -static void SlabReset(MemoryContext context); -static void SlabDelete(MemoryContext context); -static Size SlabGetChunkSpace(MemoryContext context, void *pointer); -static bool SlabIsEmpty(MemoryContext context); -static void SlabStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); -#ifdef MEMORY_CONTEXT_CHECKING -static void SlabCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for Slab contexts. - */ -static const MemoryContextMethods SlabMethods = { - SlabAlloc, - SlabFree, - SlabRealloc, - SlabReset, - SlabDelete, - SlabGetChunkSpace, - SlabIsEmpty, - SlabStats -#ifdef MEMORY_CONTEXT_CHECKING - ,SlabCheck -#endif -}; +} SlabBlock; +#define SlabBlockGetPointer(slab, block, idx) \ + (void *) (((char *) block + sizeof(SlabBlock)) + SMALL_CHUNK_SIZE + ((idx) * (slab)->fullChunkSize)) +#define SlabFirstChunkStart(block) \ + ((char *) block + sizeof(SlabBlock) + SMALL_CHUNK_SIZE) +#define SlabPointerGetIdx(slab, block, pointer) \ + (((char *) pointer - SlabFirstChunkStart(block)) / slab->fullChunkSize) /* * SlabContextCreate @@ -168,8 +111,7 @@ static const MemoryContextMethods SlabMethods = { * blockSize: allocation block size * chunkSize: allocation chunk size * - * The chunkSize may not exceed: - * MAXALIGN_DOWN(SIZE_MAX) - MAXALIGN(sizeof(SlabBlock)) - sizeof(SlabChunk) + * The chunkSize may not exceed SMALL_CHUNK_LIMIT */ MemoryContext SlabContextCreate(MemoryContext parent, @@ -184,19 +126,14 @@ SlabContextCreate(MemoryContext parent, SlabContext *slab; int i; - /* Assert we padded SlabChunk properly */ - StaticAssertStmt(sizeof(SlabChunk) == MAXALIGN(sizeof(SlabChunk)), - "sizeof(SlabChunk) is not maxaligned"); - StaticAssertStmt(offsetof(SlabChunk, slab) + sizeof(MemoryContext) == - sizeof(SlabChunk), - "padding calculation in SlabChunk is wrong"); + Assert(chunkSize <= SMALL_CHUNK_LIMIT); /* Make sure the linked list node fits inside a freed chunk */ if (chunkSize < sizeof(int)) chunkSize = sizeof(int); - /* chunk, including SLAB header (both addresses nicely aligned) */ - fullChunkSize = sizeof(SlabChunk) + MAXALIGN(chunkSize); + /* chunk, including small chunk header (both addresses nicely aligned) */ + fullChunkSize = SMALL_CHUNK_SIZE + MAXALIGN(chunkSize); /* Make sure the block can store at least one chunk. */ if (blockSize < fullChunkSize + sizeof(SlabBlock)) @@ -265,7 +202,7 @@ SlabContextCreate(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) slab, T_SlabContext, - &SlabMethods, + MCTX_SLAB_ID, parent, name); @@ -279,7 +216,7 @@ SlabContextCreate(MemoryContext parent, * The code simply frees all the blocks in the context - we don't keep any * keeper blocks or anything like that. */ -static void +void SlabReset(MemoryContext context) { int i; @@ -322,7 +259,7 @@ SlabReset(MemoryContext context) * SlabDelete * Free all memory which is allocated in the given context. */ -static void +void SlabDelete(MemoryContext context) { /* Reset to release all the SlabBlocks */ @@ -336,12 +273,12 @@ SlabDelete(MemoryContext context) * Returns pointer to allocated memory of given size or NULL if * request could not be completed; memory is added to the slab. */ -static void * +void * SlabAlloc(MemoryContext context, Size size) { SlabContext *slab = castNode(SlabContext, context); SlabBlock *block; - SlabChunk *chunk; + void *pointer; int idx; Assert(slab); @@ -370,16 +307,14 @@ SlabAlloc(MemoryContext context, Size size) block->nfree = slab->chunksPerBlock; block->firstFreeChunk = 0; + block->slab = slab; /* * Put all the chunks on a freelist. Walk the chunks and point each * one to the next one. */ for (idx = 0; idx < slab->chunksPerBlock; idx++) - { - chunk = SlabBlockGetChunk(slab, block, idx); - *(int32 *) SlabChunkGetPointer(chunk) = (idx + 1); - } + *(int32 *) SlabBlockGetPointer(slab, block, idx) = (idx + 1); /* * And add it to the last freelist with all chunks empty. @@ -411,8 +346,8 @@ SlabAlloc(MemoryContext context, Size size) /* make sure the chunk index is valid, and that it's marked as empty */ Assert((idx >= 0) && (idx < slab->chunksPerBlock)); - /* compute the chunk location block start (after the block header) */ - chunk = SlabBlockGetChunk(slab, block, idx); + /* compute the pointer */ + pointer = SlabBlockGetPointer(slab, block, idx); /* * Update the block nfree count, and also the minFreeChunks as we've @@ -426,8 +361,8 @@ SlabAlloc(MemoryContext context, Size size) * Remove the chunk from the freelist head. The index of the next free * chunk is stored in the chunk itself. */ - VALGRIND_MAKE_MEM_DEFINED(SlabChunkGetPointer(chunk), sizeof(int32)); - block->firstFreeChunk = *(int32 *) SlabChunkGetPointer(chunk); + VALGRIND_MAKE_MEM_DEFINED(pointer, sizeof(int32)); + block->firstFreeChunk = *(int32 *) pointer; Assert(block->firstFreeChunk >= 0); Assert(block->firstFreeChunk <= slab->chunksPerBlock); @@ -464,54 +399,65 @@ SlabAlloc(MemoryContext context, Size size) slab->minFreeChunks = 0; /* Prepare to initialize the chunk header. */ - VALGRIND_MAKE_MEM_UNDEFINED(chunk, sizeof(SlabChunk)); - - chunk->block = block; - chunk->slab = slab; + VALGRIND_MAKE_MEM_UNDEFINED((char *) pointer - SMALL_CHUNK_SIZE, SMALL_CHUNK_SIZE); #ifdef MEMORY_CONTEXT_CHECKING + GenericChunkHeaderEncode(pointer, block, slab->chunkSize, slab->chunkSize, MCTX_SLAB_ID); + /* slab mark to catch clobber of "unused" space */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - SMALL_CHUNK_SIZE)) { - set_sentinel(SlabChunkGetPointer(chunk), size); - VALGRIND_MAKE_MEM_NOACCESS(((char *) chunk) + - sizeof(SlabChunk) + slab->chunkSize, - slab->fullChunkSize - - (slab->chunkSize + sizeof(SlabChunk))); + set_sentinel(pointer, size); + VALGRIND_MAKE_MEM_NOACCESS(pointer + slab->chunkSize, + slab->fullChunkSize - slab->chunkSize); } +#else + GenericChunkHeaderEncode(pointer, block, slab->chunkSize, MCTX_SLAB_ID); #endif + #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) SlabChunkGetPointer(chunk), size); + randomize_mem((char *) pointer, size); #endif Assert(slab->nblocks * slab->blockSize == context->mem_allocated); - return SlabChunkGetPointer(chunk); + return pointer; } /* * SlabFree * Frees allocated memory; memory is removed from the slab. */ -static void -SlabFree(MemoryContext context, void *pointer) +void +SlabFree(void *pointer) { int idx; - SlabContext *slab = castNode(SlabContext, context); - SlabChunk *chunk = SlabPointerGetChunk(pointer); - SlabBlock *block = chunk->block; + SlabContext *slab; + SlabBlock *block; + Size chunksize; + Size blockoffset; +#ifdef MEMORY_CONTEXT_CHECKING + Size reqsize; + + GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset, &reqsize); +#else + GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset); +#endif + + block = (SlabBlock *) ((char *) pointer - blockoffset); + slab = block->slab; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - SMALL_CHUNK_SIZE)) if (!sentinel_ok(pointer, slab->chunkSize)) elog(WARNING, "detected write past chunk end in %s %p", - slab->header.name, chunk); + slab->header.name, pointer); #endif /* compute index of the chunk with respect to block start */ - idx = SlabChunkIndex(slab, block, chunk); + idx = SlabPointerGetIdx(slab, block, pointer); /* add chunk to freelist, and update block nfree count */ *(int32 *) pointer = block->firstFreeChunk; @@ -527,6 +473,10 @@ SlabFree(MemoryContext context, void *pointer) slab->chunkSize - sizeof(int32)); #endif +#ifdef MEMORY_CONTEXT_CHECKING + GenericChunkHeaderEncode(pointer, block, chunksize, 0, MCTX_SLAB_ID); +#endif + /* remove the block from a freelist */ dlist_delete(&block->node); @@ -560,13 +510,13 @@ SlabFree(MemoryContext context, void *pointer) { free(block); slab->nblocks--; - context->mem_allocated -= slab->blockSize; + slab->header.mem_allocated -= slab->blockSize; } else dlist_push_head(&slab->freelist[block->nfree], &block->node); Assert(slab->nblocks >= 0); - Assert(slab->nblocks * slab->blockSize == context->mem_allocated); + Assert(slab->nblocks * slab->blockSize == slab->header.mem_allocated); } /* @@ -582,10 +532,23 @@ SlabFree(MemoryContext context, void *pointer) * rather pointless - Slab is meant for chunks of constant size, and moreover * realloc is usually used to enlarge the chunk. */ -static void * -SlabRealloc(MemoryContext context, void *pointer, Size size) +void * +SlabRealloc(void *pointer, Size size) { - SlabContext *slab = castNode(SlabContext, context); + SlabContext *slab; + SlabBlock *block; + Size chunksize; + Size blockoffset; +#ifdef MEMORY_CONTEXT_CHECKING + Size reqsize; + + GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset, &reqsize); +#else + GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset); +#endif + + block = (SlabBlock *) ((char *) pointer - blockoffset); + slab = block->slab; Assert(slab); @@ -597,15 +560,54 @@ SlabRealloc(MemoryContext context, void *pointer, Size size) return NULL; /* keep compiler quiet */ } +/* + * SlabGetChunkContext + */ +MemoryContext +SlabGetChunkContext(void *pointer) +{ + SlabContext *slab; + SlabBlock *block; + Size chunksize; + Size blockoffset; +#ifdef MEMORY_CONTEXT_CHECKING + Size reqsize; + + GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset, &reqsize); +#else + GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset); +#endif + + block = (SlabBlock *) ((char *) pointer - blockoffset); + slab = block->slab; + + Assert(slab); + + return &slab->header; +} + /* * SlabGetChunkSpace * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -SlabGetChunkSpace(MemoryContext context, void *pointer) +Size +SlabGetChunkSpace(void *pointer) { - SlabContext *slab = castNode(SlabContext, context); + SlabContext *slab; + SlabBlock *block; + Size chunksize; + Size blockoffset; +#ifdef MEMORY_CONTEXT_CHECKING + Size reqsize; + + GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset, &reqsize); +#else + GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset); +#endif + + block = (SlabBlock *) ((char *) pointer - blockoffset); + slab = block->slab; Assert(slab); @@ -616,7 +618,7 @@ SlabGetChunkSpace(MemoryContext context, void *pointer) * SlabIsEmpty * Is an Slab empty of any allocated space? */ -static bool +bool SlabIsEmpty(MemoryContext context) { SlabContext *slab = castNode(SlabContext, context); @@ -635,7 +637,7 @@ SlabIsEmpty(MemoryContext context) * totals: if not NULL, add stats about this context into *totals. * print_to_stderr: print stats to stderr if true, elog otherwise. */ -static void +void SlabStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, @@ -697,7 +699,7 @@ SlabStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void SlabCheck(MemoryContext context) { int i; @@ -742,16 +744,16 @@ SlabCheck(MemoryContext context) nfree = 0; while (idx < slab->chunksPerBlock) { - SlabChunk *chunk; + void *pointer; /* count the chunk as free, add it to the bitmap */ nfree++; slab->freechunks[idx] = true; /* read index of the next free chunk */ - chunk = SlabBlockGetChunk(slab, block, idx); - VALGRIND_MAKE_MEM_DEFINED(SlabChunkGetPointer(chunk), sizeof(int32)); - idx = *(int32 *) SlabChunkGetPointer(chunk); + pointer = SlabBlockGetPointer(slab, block, idx); + VALGRIND_MAKE_MEM_DEFINED(pointer, sizeof(int32)); + idx = *(int32 *) pointer; } for (j = 0; j < slab->chunksPerBlock; j++) @@ -759,22 +761,29 @@ SlabCheck(MemoryContext context) /* non-zero bit in the bitmap means chunk the chunk is used */ if (!slab->freechunks[j]) { - SlabChunk *chunk = SlabBlockGetChunk(slab, block, j); + void *pointer = SlabBlockGetPointer(slab, block, j); + SlabBlock *sblock; + Size chunksize; + Size blockoffset; + Size reqSize; + + GenericChunkHeaderDecode(pointer, &chunksize, &blockoffset, &reqSize); + sblock = (SlabBlock *) ((char *) pointer) - blockoffset; - /* chunks have both block and slab pointers, so check both */ - if (chunk->block != block) - elog(WARNING, "problem in slab %s: bogus block link in block %p, chunk %p", - name, block, chunk); + /* check the blockoffset correctly points back to the block */ + if (sblock != block) + elog(WARNING, "problem in slab %s: bogus block link in block %p, pointer %p", + name, block, pointer); - if (chunk->slab != slab) - elog(WARNING, "problem in slab %s: bogus slab link in block %p, chunk %p", - name, block, chunk); + if (sblock->slab != slab) + elog(WARNING, "problem in slab %s: bogus slab link in block %p, pointer %p", + name, block, pointer); /* there might be sentinel (thanks to alignment) */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) - if (!sentinel_ok(chunk, slab->chunkSize)) - elog(WARNING, "problem in slab %s: detected write past chunk end in block %p, chunk %p", - name, block, chunk); + if (slab->chunkSize < slab->fullChunkSize) + if (!sentinel_ok(pointer, slab->chunkSize)) + elog(WARNING, "problem in slab %s: detected write past chunk end in block %p, pointer %p", + name, block, pointer); } } diff --git a/src/include/nodes/memnodes.h b/src/include/nodes/memnodes.h index bbbe151e39..925b42b768 100644 --- a/src/include/nodes/memnodes.h +++ b/src/include/nodes/memnodes.h @@ -59,11 +59,12 @@ typedef struct MemoryContextMethods { void *(*alloc) (MemoryContext context, Size size); /* call this free_p in case someone #define's free() */ - void (*free_p) (MemoryContext context, void *pointer); - void *(*realloc) (MemoryContext context, void *pointer, Size size); + void (*free_p) (void *pointer); + void *(*realloc) (void *pointer, Size size); void (*reset) (MemoryContext context); void (*delete_context) (MemoryContext context); - Size (*get_chunk_space) (MemoryContext context, void *pointer); + MemoryContext (*get_chunk_context) (void *pointer); + Size (*get_chunk_space) (void *pointer); bool (*is_empty) (MemoryContext context); void (*stats) (MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, diff --git a/src/include/utils/memutils.h b/src/include/utils/memutils.h index 495d1af201..244f7bf4ff 100644 --- a/src/include/utils/memutils.h +++ b/src/include/utils/memutils.h @@ -79,6 +79,7 @@ extern void MemoryContextDeleteChildren(MemoryContext context); extern void MemoryContextSetIdentifier(MemoryContext context, const char *id); extern void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent); +extern MemoryContext GetMemoryChunkContext(void *pointer); extern Size GetMemoryChunkSpace(void *pointer); extern MemoryContext MemoryContextGetParent(MemoryContext context); extern bool MemoryContextIsEmpty(MemoryContext context); @@ -98,53 +99,6 @@ extern bool MemoryContextContains(MemoryContext context, void *pointer); #define MemoryContextCopyAndSetIdentifier(cxt, id) \ MemoryContextSetIdentifier(cxt, MemoryContextStrdup(cxt, id)) -/* - * GetMemoryChunkContext - * Given a currently-allocated chunk, determine the context - * it belongs to. - * - * All chunks allocated by any memory context manager are required to be - * preceded by the corresponding MemoryContext stored, without padding, in the - * preceding sizeof(void*) bytes. A currently-allocated chunk must contain a - * backpointer to its owning context. The backpointer is used by pfree() and - * repalloc() to find the context to call. - */ -#ifndef FRONTEND -static inline MemoryContext -GetMemoryChunkContext(void *pointer) -{ - MemoryContext context; - - /* - * Try to detect bogus pointers handed to us, poorly though we can. - * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an - * allocated chunk. - */ - Assert(pointer != NULL); - Assert(pointer == (void *) MAXALIGN(pointer)); - - /* - * OK, it's probably safe to look at the context. - */ - context = *(MemoryContext *) (((char *) pointer) - sizeof(void *)); - - AssertArg(MemoryContextIsValid(context)); - - return context; -} -#endif - -/* - * This routine handles the context-type-independent part of memory - * context creation. It's intended to be called from context-type- - * specific creation routines, and noplace else. - */ -extern void MemoryContextCreate(MemoryContext node, - NodeTag tag, - const MemoryContextMethods *methods, - MemoryContext parent, - const char *name); - extern void HandleLogMemoryContextInterrupt(void); extern void ProcessLogMemoryContextInterrupt(void); diff --git a/src/include/utils/memutils_generichdr.h b/src/include/utils/memutils_generichdr.h new file mode 100644 index 0000000000..82d06715ad --- /dev/null +++ b/src/include/utils/memutils_generichdr.h @@ -0,0 +1,265 @@ +/*------------------------------------------------------------------------- + * + * memutils_generichdr.h + * Contains various inlined functions which can be used by implementations + * of MemoryContexts to use as a memory chunk header. Implementations may + * choose to implement their own header. The only requirement is that the + * 3-bits directly prior to the pointer must be set to the + * MemoryContextMethodID of the given context. + * + * This generic chunk header allows the encoding of various details about the + * memory chunk. Generally, these headers are 8 bytes in length, however for + * larger allocations 24 bytes are required. We refer to the former as + * "small" headers and the latter as "large" headers. + * + * Both small and large headers have a 8-byte portion directly prior to the + * memory pointer for the chunk. We encode 4 separate pieces of information + * into these 8 bytes. These are as follows in order of least significant bit + * first: + * + * 1. 3-bits to indicate the MemoryContextMethodID + * 2. 1-bit to indicate if the chunk is small or large + * 3. 30-bits to indicate the size of the chunk + * 4. 30-bits to indicate the number of bytes that must be subtracted from the + * pointer to obtain the address of the block that the pointer is stored on + * + * Memory allocations where the size of the chunk or the block offset is a + * value that consumes more than 30-bits (1GB) must use a large chunk. + * + * Large chunks, as mentioned above, also contain a 8-byte header, however + * the 30-bit portions #3 and #4 above are unused. Instead the chunk size and + * block offset are stored directly prior to the 8-byte chunk header in the + * following form: + * + * <Size block offset><Size chunk size><8 byte header> + * + * Which is 24 bytes when sizeof(Size) is 8 and 16 bytes when sizeof(Size) is + * 4. + * + * When MEMORY_CONTEXT_CHECKING is defined, both small and large headers store + * an additional Size variable which directly prefixes the existing chunk. + * This additional Size field is used to store the requested size of the + * allocation. This can be used by the MemoryContexts implementation to + * perform additional checks to help ensure the code is correct. For example, + * setting sentinal bytes to help ensure that no code overruns the memory + * allocation. + * + * Interface: + * GenericChunkHeaderSize: + * Used to predetermine the size of the chunk. + * + * GenericChunkHeaderDecode: + * Given a pointer to the memory, determine the size of the chunk and + * the number of bytes to subtract from the pointer to obtain the pointer + * to the block. The requested_size is also decoded when + * MEMORY_CONTEXT_CHECKING is defined. + * + * GenericChunkHeaderEncode: + * Given a pointer to the memory and a pointer to the block, determine + * the bytes offset for the block and encode that and the + * MemoryContextMethodID into the chunk. Also encode the chunk size and + * optionally, the requested_size when MEMORY_CONTEXT_CHECKING is + * defined. + * + * Also exports: + * SMALL_CHUNK_LIMIT + * SMALL_CHUNK_SIZE + * LARGE_CHUNK_SIZE + * + * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/utils/memutils_generichdr.h + * + *------------------------------------------------------------------------- + */ + +#ifndef MEMUTILS_GENERICHDR_H +#define MEMUTILS_GENERICHDR_H + +#include "utils/memutils_internal.h" + +/* + * The threshold, above which a chunk becomes large. The maximum value that + * can be stored in 30-bits. + */ +#define SMALL_CHUNK_LIMIT 0x3FFFFFFF + +/* + * Bit mask with 30 of the least significant bits on. Generally the same as + * SMALL_CHUNK_LIMIT, but kept separate so that SMALL_CHUNK_LIMIT can be + * lowered to make testing large chunks easier. + */ +#define SMALL_CHUNK_SIZE_MASK 0x3FFFFFFF + +/* + * The value to AND onto the 8-byte header to determine if it's a large chunk. + */ +#define LARGE_CHUNK_MASK (1 << 3) + +#ifndef MEMORY_CONTEXT_CHECKING +#define SMALL_CHUNK_SIZE sizeof(uint64) +#define LARGE_CHUNK_SIZE (sizeof(uint64) + (sizeof(Size) * 2)) +#else +#define SMALL_CHUNK_SIZE (sizeof(uint64) + sizeof(Size)) +#define LARGE_CHUNK_SIZE (sizeof(uint64) + (sizeof(Size) * 3)) +#endif + +#define LargeChunkGetChunkSizePtr(p) (Size *) (((char *) (p)) - sizeof(uint64) - sizeof(Size)) +#define LargeChunkGetBlockOffsetPtr(p) (Size *) (((char *) (p)) - sizeof(uint64) - (sizeof(Size) * 2)) + +#ifdef MEMORY_CONTEXT_CHECKING +#define LargeChunkGetRequestedSizePtr(p) (Size *) (((char *) (p)) - sizeof(uint64) - (sizeof(Size) * 3)) +#endif + +/* Get a pointer to the uint64 header for either a small or large chunk */ +#define ChunkGetHeaderPtr(p) ((uint64 *) (((char *) p) - sizeof(uint64))) + +/* + * From a small or large chunk's header uint64 value, get the context method id + */ +#define ChunkHdrGetMethodId(h) ((h) & 7) + +#define SmallChunkHdrGetChunkSize(h) (((h) >> 4) & SMALL_CHUNK_SIZE_MASK) +#define SmallChunkHdrGetBlockOffset(h) (((h) >> 34) & SMALL_CHUNK_SIZE_MASK) + +#ifdef MEMORY_CONTEXT_CHECKING +#define SmallChunkGetRequestedSizePtr(p) (Size *) (((char *) (p)) - sizeof(uint64) - sizeof(Size)) +#endif + + /* + * Determine if offset or size justify requiring a large chunk. Since + * SMALL_CHUNK_LIMIT is a power of 2, we can bitmask OR offset and size to + * get a slightly more efficient way of checking if either is larger than + * SMALL_CHUNK_LIMIT. + */ +#define LargeChunkRequired(offset, size) (((offset) | (size)) > SMALL_CHUNK_LIMIT) + + /* From a given chunk header, return true if it's a large chunk */ +#define IsLargeChunk(h) ((h) & LARGE_CHUNK_MASK) + +/* + * GenericChunkHeaderSize + * Return the size of chunk header required to store details about a + * chunk with the given blockoffset and chunkisize. + */ +static inline Size +GenericChunkHeaderSize(Size blockoffset, Size chunksize) +{ + return LargeChunkRequired(blockoffset, chunksize) ? LARGE_CHUNK_SIZE : SMALL_CHUNK_SIZE; +} + +/* + * GenericChunkHeaderDecode + * Decode the generic chunk header preceeding 'pointer' and populate + * 'chunksize' and 'blockoffset'. Return the size of the generic header. + */ +static inline Size +#ifdef MEMORY_CONTEXT_CHECKING +GenericChunkHeaderDecode(void *pointer, Size *chunksize, Size *blockoffset, + Size *requested_size) +#else +GenericChunkHeaderDecode(void *pointer, Size *chunksize, Size *blockoffset) +#endif +{ + uint64 header = (uint64) *ChunkGetHeaderPtr(pointer); + + if (unlikely(IsLargeChunk(header))) + { + *chunksize = (Size) *LargeChunkGetChunkSizePtr(pointer); + *blockoffset = (Size) *LargeChunkGetBlockOffsetPtr(pointer); + +#ifdef MEMORY_CONTEXT_CHECKING + *requested_size = (Size) *LargeChunkGetRequestedSizePtr(pointer); +#endif + return LARGE_CHUNK_SIZE; + } + else + { + *chunksize = SmallChunkHdrGetChunkSize(header); + *blockoffset = SmallChunkHdrGetBlockOffset(header); +#ifdef MEMORY_CONTEXT_CHECKING + *requested_size = (Size) *SmallChunkGetRequestedSizePtr(pointer); +#endif + + return SMALL_CHUNK_SIZE; + } +} + +static inline void +#ifdef MEMORY_CONTEXT_CHECKING +GenericChunkHeaderEncode(void *pointer, void *block, Size chunksize, + Size requested_size, MemoryContextMethodID methodid) +#else +GenericChunkHeaderEncode(void *pointer, void *block, Size chunksize, + MemoryContextMethodID methodid) +#endif +{ + uint64 *p_header = ChunkGetHeaderPtr(pointer); + Size blockoffset = (char *) pointer - (char *) block; + + /* Check if we need a large chunk */ + if (unlikely(LargeChunkRequired(blockoffset, chunksize))) + { + Size *p_chunksize = LargeChunkGetChunkSizePtr(pointer); + Size *p_blockoffset = LargeChunkGetBlockOffsetPtr(pointer); +#ifdef MEMORY_CONTEXT_CHECKING + Size *p_requestedsize = LargeChunkGetRequestedSizePtr(pointer); +#endif + + /* Encode the 8-byte header */ + *p_header = LARGE_CHUNK_MASK | methodid; + + /* Set the chunk size and block offset */ + *p_chunksize = chunksize; + + *p_blockoffset = blockoffset; + +#ifdef MEMORY_CONTEXT_CHECKING + *p_requestedsize = requested_size; +#endif + } + else + { + *p_header = (blockoffset << 34) | (chunksize << 4) | methodid; +#ifdef MEMORY_CONTEXT_CHECKING + *SmallChunkGetRequestedSizePtr(pointer) = requested_size; +#endif + } + +#ifdef USE_ASSERT_CHECKING + /* verify that we decode the values the same as we've just encoded them */ + { + Size chsz, blkoff; +#ifdef MEMORY_CONTEXT_CHECKING + Size reqsz; + + GenericChunkHeaderDecode(pointer, &chsz, &blkoff, &reqsz); + + Assert(reqsz == requested_size); +#else + GenericChunkHeaderDecode(pointer, &chsz, &blkoff); +#endif + Assert(chsz == chunksize); + Assert(blkoff == blockoffset); + Assert(blkoff > 0); + Assert(GetMemoryChunkMethodID(pointer) == methodid); + } +#endif + +} + +/* cleanup all internal definitions */ +#undef LARGE_CHUNK_MASK +#undef LargeChunkGetChunkSizePtr +#undef LargeChunkGetBlockOffsetPtr +#undef LargeChunkGetRequestedSizePtr +#undef ChunkGetHeaderPtr +#undef ChunkHdrGetMethodId +#undef SmallChunkHdrGetChunkSize +#undef SmallChunkHdrGetBlockOffset +#undef SmallChunkGetRequestedSizePtr +#undef LargeChunkRequired +#undef IsLargeChunk + +#endif /* MEMUTILS_GENERICHDR_H */ diff --git a/src/include/utils/memutils_internal.h b/src/include/utils/memutils_internal.h new file mode 100644 index 0000000000..ab94115ee5 --- /dev/null +++ b/src/include/utils/memutils_internal.h @@ -0,0 +1,117 @@ +/*------------------------------------------------------------------------- + * + * memutils_internal.h + * This file contains declarations for memory allocation utility + * functions for internal use. + * + * + * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/utils/memutils_internal.h + * + *------------------------------------------------------------------------- + */ + +#ifndef MEMUTILS_INTERNAL_H +#define MEMUTILS_INTERNAL_H + +#include "utils/memutils.h" + +extern void *AllocSetAlloc(MemoryContext context, Size size); +extern void AllocSetFree(void *pointer); +extern void *AllocSetRealloc(void *pointer, Size size); +extern void AllocSetReset(MemoryContext context); +extern void AllocSetDelete(MemoryContext context); +extern MemoryContext AllocSetGetChunkContext(void *pointer); +extern Size AllocSetGetChunkSpace(void *pointer); +extern bool AllocSetIsEmpty(MemoryContext context); +extern void AllocSetStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); + +#ifdef MEMORY_CONTEXT_CHECKING +extern void AllocSetCheck(MemoryContext context); +#endif + + +extern void *GenerationAlloc(MemoryContext context, Size size); +extern void GenerationFree(void *pointer); +extern void *GenerationRealloc(void *pointer, Size size); +extern void GenerationReset(MemoryContext context); +extern void GenerationDelete(MemoryContext context); +extern MemoryContext GenerationGetChunkContext(void *pointer); +extern Size GenerationGetChunkSpace(void *pointer); +extern bool GenerationIsEmpty(MemoryContext context); +extern void GenerationStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); + +#ifdef MEMORY_CONTEXT_CHECKING +extern void GenerationCheck(MemoryContext context); +#endif + + +/* + * These functions implement the MemoryContext API for Slab contexts. + */ +extern void *SlabAlloc(MemoryContext context, Size size); +extern void SlabFree(void *pointer); +extern void *SlabRealloc(void *pointer, Size size); +extern void SlabReset(MemoryContext context); +extern void SlabDelete(MemoryContext context); +extern MemoryContext SlabGetChunkContext(void *pointer); +extern Size SlabGetChunkSpace(void *pointer); +extern bool SlabIsEmpty(MemoryContext context); +extern void SlabStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); +#ifdef MEMORY_CONTEXT_CHECKING +extern void SlabCheck(MemoryContext context); +#endif + +/* + * MemoryContextMethodID + * A unique identifier for each MemoryContext implementation which + * indicates the index into the mcxt_methods[] array. See mcxt.c. + */ +typedef enum MemoryContextMethodID +{ + MCTX_ASET_ID = 0, + MCTX_GENERATION_ID, + MCTX_SLAB_ID, +} MemoryContextMethodID; + +/* + * This routine handles the context-type-independent part of memory + * context creation. It's intended to be called from context-type- + * specific creation routines, and noplace else. + */ +extern void MemoryContextCreate(MemoryContext node, + NodeTag tag, + MemoryContextMethodID method_id, + MemoryContext parent, + const char *name); + +static inline MemoryContextMethodID +GetMemoryChunkMethodID(void *pointer) +{ + uint64 header; + + /* + * Try to detect bogus pointers handed to us, poorly though we can. + * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an + * allocated chunk. + */ + Assert(pointer != NULL); + Assert(pointer == (void *) MAXALIGN(pointer)); + + header = *((uint64 *) ((char *) pointer - sizeof(uint64))); + + return header & 7; +} + +#endif /* MEMUTILS_INTERNAL_H */ -- 2.35.1.windows.2
10gb_sort_bench_2022-07-12.png (image/png, 97.9K) download view image
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-07-12 17:22  Yura Sokolov <y.sokolov@postgrespro.ru>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 1 reply; 152+ messages in thread

From: Yura Sokolov @ 2022-07-12 17:22 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Good day, David.

В Вт, 12/07/2022 в 17:01 +1200, David Rowley пишет:
> Over on [1], I highlighted that 40af10b57 (Use Generation memory
> contexts to store tuples in sorts) could cause some performance
> regressions for sorts when the size of the tuple is exactly a power of
> 2.  The reason for this is that the chunk header for generation.c
> contexts is 8 bytes larger (on 64-bit machines) than the aset.c chunk
> header. This means that we can store fewer tuples per work_mem during
> the sort and that results in more batches being required.
> 
> As I write this, this regression is still marked as an open item for
> PG15 in [2]. So I've been working on this to try to assist the
> discussion about if we need to do anything about that for PG15.
> 
> Over on [3], I mentioned that Andres came up with an idea and a
> prototype patch to reduce the chunk header size across the board by
> storing the context type in the 3 least significant bits in a uint64
> header.
> 
> I've taken Andres' patch and made some quite significant changes to
> it. In the patch's current state, the sort performance regression in
> PG15 vs PG14 is fixed. The generation.c context chunk header has been
> reduced to 8 bytes from the previous 24 bytes as it is in master.
> aset.c context chunk header is now 8 bytes instead of 16 bytes.
> 
> We can use this 8-byte chunk header by using the remaining 61-bits of
> the uint64 header to encode 2 30-bit values to store the chunk size
> and also the number of bytes we must subtract from the given pointer
> to find the block that the chunk is stored on.  Once we have the
> block, we can find the owning context by having a pointer back to the
> context from the block.  For memory allocations that are larger than
> what can be stored in 30 bits, the chunk header gets an additional two
> Size fields to store the chunk_size and the block offset.  We can tell
> the difference between the 2 chunk sizes by looking at the spare 1-bit
> the uint64 portion of the header.

I don't get, why "large chunk" needs additional fields for size and
offset.
Large allocation sizes are certainly rounded to page size.
And allocations which doesn't fit 1GB we could easily round to 1MB.
Then we could simply store `size>>20`.
It will limit MaxAllocHugeSize to `(1<<(30+20))-1` - 1PB. Doubdfully we
will deal with such huge allocations in near future.

And to limit block offset, we just have to limit maxBlockSize to 1GB,
which is quite reasonable limitation.
Chunks that are larger than maxBlockSize goes to separate blocks anyway,
therefore they have small block offset.

> Aside from speeding up the sort case, this also seems to have a good
> positive performance impact on pgbench read-only workload with -M
> simple. I'm seeing about a 17% performance increase on my AMD
> Threadripper machine.
> 
> master + Reduced Memory Context Chunk Overhead
> drowley@amd3990x:~$ pgbench -S -T 60 -j 156 -c 156 -M simple postgres
> tps = 1876841.953096 (without initial connection time)
> tps = 1919605.408254 (without initial connection time)
> tps = 1891734.480141 (without initial connection time)
> 
> Master
> drowley@amd3990x:~$ pgbench -S -T 60 -j 156 -c 156 -M simple postgres
> tps = 1632248.236962 (without initial connection time)
> tps = 1615663.151604 (without initial connection time)
> tps = 1602004.146259 (without initial connection time)

Trick with 3bit context type is great.

> The attached .png file shows the same results for PG14 and PG15 as I
> showed in the blog [4] where I discovered the regression and adds the
> results from current master + the attached patch. See bars in orange.
> You can see that the regression at 64MB work_mem is fixed. Adding some
> tracing to the sort shows that we're now doing 671745 tuples per batch
> instead of 576845 tuples. This reduces the number of batches from 245
> down to 210.
> 
> Drawbacks:
> 
> There is at least one. It might be major; to reduce the AllocSet chunk
> header from 16 bytes down to 8 bytes I had to get rid of the freelist
> pointer that was reusing the "aset" field in the chunk header struct.
> This works now by storing that pointer in the actual palloc'd memory.
> This could lead to pretty hard-to-trace bugs if we have any code that
> accidentally writes to memory after pfree.  The slab.c context already
> does this, but that's far less commonly used.  If we decided this was
> unacceptable then it does not change anything for the generation.c
> context.  The chunk header will still be 8 bytes instead of 24 there.
> So the sort performance regression will still be fixed.

At least we can still mark free list pointer as VALGRIND_MAKE_MEM_NOACCESS
and do VALGRIND_MAKE_MEM_DEFINED on fetching from free list, can we?

> To improve this situation, we might be able code it up so that
> MEMORY_CONTEXT_CHECKING builds add an additional freelist pointer to
> the header and also write it to the palloc'd memory then verify
> they're set to the same thing when we reuse a chunk from the freelist.
> If they're not the same then MEMORY_CONTEXT_CHECKING builds could
> either spit out a WARNING or ERROR for this case.  That would make it
> pretty easy for developers to find their write after pfree bugs. This
> might actually be better than the Valgrind  detection method that we
> have for this today.
> 
> Patch:
> 
> I've attached the WIP patch. At this stage, I'm more looking for a
> design review. I'm not aware of any bugs, but I am aware that I've not
> tested with Valgrind. I've not paid a great deal of attention to
> updating the Valgrind macros at all.
> 
> I'll add this to the September CF.  I'm submitting now due to the fact
> that we still have an open item in PG15 for the sort regression and
> the existence of this patch might cause us to decide whether we can
> defer fixing that to PG16 by way of the method in this patch, or
> revert 40af10b57.
> 
> Benchmark code in [5].
> 
> David
> 
> [1] https://www.postgresql.org/message-id/CAApHDvqXpLzav6dUeR5vO_RBh_feHrHMLhigVQXw9jHCyKP9PA%40mail.gma...
> [2] https://wiki.postgresql.org/wiki/PostgreSQL_15_Open_Items
> [3] https://www.postgresql.org/message-id/CAApHDvowHNSVLhMc0cnovg8PfnYQZxit-gP_bn3xkT4rZX3G0w%40mail.gma...
> [4] https://techcommunity.microsoft.com/t5/azure-database-for-postgresql/speeding-up-sort-performance-in...
> [5] https://www.postgresql.org/message-id/attachment/134161/sortbench_varcols.sh






^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-07-12 17:42  Andres Freund <andres@anarazel.de>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 2 replies; 152+ messages in thread

From: Andres Freund @ 2022-07-12 17:42 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2022-07-12 17:01:18 +1200, David Rowley wrote:
> I've taken Andres' patch and made some quite significant changes to
> it. In the patch's current state, the sort performance regression in
> PG15 vs PG14 is fixed. The generation.c context chunk header has been
> reduced to 8 bytes from the previous 24 bytes as it is in master.
> aset.c context chunk header is now 8 bytes instead of 16 bytes.

I think this is *very* cool. But I might be biased :)


> There is at least one. It might be major; to reduce the AllocSet chunk
> header from 16 bytes down to 8 bytes I had to get rid of the freelist
> pointer that was reusing the "aset" field in the chunk header struct.
> This works now by storing that pointer in the actual palloc'd memory.
> This could lead to pretty hard-to-trace bugs if we have any code that
> accidentally writes to memory after pfree.

Can't we use the same trick for allcations in the freelist as we do for the
header in a live allocation? I.e. split the 8 byte header into two and use
part of it to point to the next element in the list using the offset from the
start of the block, and part of it to indicate the size?

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-07-12 17:44  Andres Freund <andres@anarazel.de>
  parent: Yura Sokolov <y.sokolov@postgrespro.ru>
  0 siblings, 1 reply; 152+ messages in thread

From: Andres Freund @ 2022-07-12 17:44 UTC (permalink / raw)
  To: Yura Sokolov <y.sokolov@postgrespro.ru>; +Cc: David Rowley <dgrowleyml@gmail.com>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2022-07-12 20:22:57 +0300, Yura Sokolov wrote:
> I don't get, why "large chunk" needs additional fields for size and
> offset.
> Large allocation sizes are certainly rounded to page size.
> And allocations which doesn't fit 1GB we could easily round to 1MB.
> Then we could simply store `size>>20`.
> It will limit MaxAllocHugeSize to `(1<<(30+20))-1` - 1PB. Doubdfully we
> will deal with such huge allocations in near future.

What would gain by doing something like this? The storage density loss of
storing an exact size is smaller than what you propose here.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-07-13 05:20  David Rowley <dgrowleyml@gmail.com>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-07-13 05:20 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Wed, 13 Jul 2022 at 05:44, Andres Freund <andres@anarazel.de> wrote:
> On 2022-07-12 20:22:57 +0300, Yura Sokolov wrote:
> > I don't get, why "large chunk" needs additional fields for size and
> > offset.
> > Large allocation sizes are certainly rounded to page size.
> > And allocations which doesn't fit 1GB we could easily round to 1MB.
> > Then we could simply store `size>>20`.
> > It will limit MaxAllocHugeSize to `(1<<(30+20))-1` - 1PB. Doubdfully we
> > will deal with such huge allocations in near future.
>
> What would gain by doing something like this? The storage density loss of
> storing an exact size is smaller than what you propose here.

I do agree that the 16-byte additional header size overhead for
allocations >= 1GB are not really worth troubling too much over.
However, if there was some way to make it so we always had an 8-byte
header, it would simplify some of the code in places such as
AllocSetFree().   For example, (ALLOC_BLOCKHDRSZ + hdrsize +
chunksize) could be simplified at compile time if hdrsize was a known
constant.

I did consider that in all cases where the allocations are above
allocChunkLimit that the chunk is put on a dedicated block and in
fact, the blockoffset is always the same for those.  I wondered if we
could use the full 60 bits for the chunksize for those cases.  The
reason I didn't pursue that is because:

#define MaxAllocHugeSize (SIZE_MAX / 2)

That's 63-bits, so 60 isn't enough.

Yeah, we likely could reduce that without upsetting anyone.  It feels
like it'll be a while before not being able to allocate a chunk of
memory more than 1024 petabytes will be an issue, although, I do hope
to grow old enough to one day come back here at laugh at that.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-07-13 05:24  David Rowley <dgrowleyml@gmail.com>
  parent: Andres Freund <andres@anarazel.de>
  1 sibling, 0 replies; 152+ messages in thread

From: David Rowley @ 2022-07-13 05:24 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Wed, 13 Jul 2022 at 05:42, Andres Freund <andres@anarazel.de> wrote:
> > There is at least one. It might be major; to reduce the AllocSet chunk
> > header from 16 bytes down to 8 bytes I had to get rid of the freelist
> > pointer that was reusing the "aset" field in the chunk header struct.
> > This works now by storing that pointer in the actual palloc'd memory.
> > This could lead to pretty hard-to-trace bugs if we have any code that
> > accidentally writes to memory after pfree.
>
> Can't we use the same trick for allcations in the freelist as we do for the
> header in a live allocation? I.e. split the 8 byte header into two and use
> part of it to point to the next element in the list using the offset from the
> start of the block, and part of it to indicate the size?

That can't work as the next freelist item might be on some other block.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-07-13 05:41  Andres Freund <andres@anarazel.de>
  parent: Andres Freund <andres@anarazel.de>
  1 sibling, 1 reply; 152+ messages in thread

From: Andres Freund @ 2022-07-13 05:41 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2022-07-12 10:42:07 -0700, Andres Freund wrote:
> On 2022-07-12 17:01:18 +1200, David Rowley wrote:
> > There is at least one. It might be major; to reduce the AllocSet chunk
> > header from 16 bytes down to 8 bytes I had to get rid of the freelist
> > pointer that was reusing the "aset" field in the chunk header struct.
> > This works now by storing that pointer in the actual palloc'd memory.
> > This could lead to pretty hard-to-trace bugs if we have any code that
> > accidentally writes to memory after pfree.
> 
> Can't we use the same trick for allcations in the freelist as we do for the
> header in a live allocation? I.e. split the 8 byte header into two and use
> part of it to point to the next element in the list using the offset from the
> start of the block, and part of it to indicate the size?

So that doesn't work because the members in the freelist can be in different
blocks and those can be further away from each other.


Perhaps that could still made work somehow: To point to a block we don't
actually need 64bit pointers, they're always at least of some certain size -
assuming we can allocate them suitably aligned. And chunks are always 8 byte
aligned. Unfortunately that doesn't quite get us far enough - assuming a 4kB
minimum block size (larger than now, but potentially sensible as a common OS
page size), we still only get to 2^12*8 = 32kB.

It'd easily work if we made each context have an array of allocated non-huge
blocks, so that the blocks can be addressed with a small index. The overhead
of that could be reduced in the common case by embedding a small constant
sized array in the Aset.  That might actually be worth trying out.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-07-17 16:10  Yura Sokolov <y.sokolov@postgrespro.ru>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 0 replies; 152+ messages in thread

From: Yura Sokolov @ 2022-07-17 16:10 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; David Rowley <dgrowleyml@gmail.com>; +Cc: PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

В Вт, 12/07/2022 в 22:41 -0700, Andres Freund пишет:
> Hi,
> 
> On 2022-07-12 10:42:07 -0700, Andres Freund wrote:
> > On 2022-07-12 17:01:18 +1200, David Rowley wrote:
> > > There is at least one. It might be major; to reduce the AllocSet chunk
> > > header from 16 bytes down to 8 bytes I had to get rid of the freelist
> > > pointer that was reusing the "aset" field in the chunk header struct.
> > > This works now by storing that pointer in the actual palloc'd memory.
> > > This could lead to pretty hard-to-trace bugs if we have any code that
> > > accidentally writes to memory after pfree.
> > 
> > Can't we use the same trick for allcations in the freelist as we do for the
> > header in a live allocation? I.e. split the 8 byte header into two and use
> > part of it to point to the next element in the list using the offset from the
> > start of the block, and part of it to indicate the size?
> 
> So that doesn't work because the members in the freelist can be in different
> blocks and those can be further away from each other.
> 
> 
> Perhaps that could still made work somehow: To point to a block we don't
> actually need 64bit pointers, they're always at least of some certain size -
> assuming we can allocate them suitably aligned. And chunks are always 8 byte
> aligned. Unfortunately that doesn't quite get us far enough - assuming a 4kB
> minimum block size (larger than now, but potentially sensible as a common OS
> page size), we still only get to 2^12*8 = 32kB.

Well, we actually have freelists for 11 size classes.
It is just 11 pointers.
We could embed this 88 bytes in every ASet block and then link blocks.
And then in every block have 44 bytes for in-block free lists.
Total overhead is 132 bytes per-block.
Or 110 if we limit block size to 65k*8b=512kb.

With double-linked block lists (176bytes per block + 44bytes for in-block lists
= 220bytes), we could track block fullness and deallocate it if it doesn't
contain any alive alocation. Therefore "generational" and "slab" allocators
will be less useful.

But CPU overhead will be noticeable.

> It'd easily work if we made each context have an array of allocated non-huge
> blocks, so that the blocks can be addressed with a small index. The overhead
> of that could be reduced in the common case by embedding a small constant
> sized array in the Aset.  That might actually be worth trying out.
> 
> Greetings,
> 
> Andres Freund
> 
> 






^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-09 12:53  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-08-09 12:53 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Wed, 13 Jul 2022 at 17:20, David Rowley <dgrowleyml@gmail.com> wrote:
> I did consider that in all cases where the allocations are above
> allocChunkLimit that the chunk is put on a dedicated block and in
> fact, the blockoffset is always the same for those.  I wondered if we
> could use the full 60 bits for the chunksize for those cases.  The
> reason I didn't pursue that is because:

As it turns out, we don't really need to explicitly store the chunk
size for chunks which are on dedicated blocks.  We can just calculate
this by subtracting the pointer to the memory from the block's endptr.
The block offset is always fixed too, like I mentioned above.

I've now revised the patch to completely get rid of the concept of
"large" chunks and instead memory chunks are always 8 bytes in size.
I've created a struct to this effect and named it MemoryChunk. All
memory contexts make use of this new struct.  The header bit which I
was previously using to denote a "large" chunk now marks if the chunk
is "external", meaning that the MemoryChunk does not have knowledge of
the chunk size and/or block offset. The MemoryContext itself is
expected to manage this when the chunk is external.   I've coded up
aset.c and generation.c to always use these external chunks when size
> set->allocChunkLimit.  There is now a coding pattern like the
following (taken from AllocSetRealloc:

if (MemoryChunkIsExternal(chunk))
{
    block = ExternalChunkGetBlock(chunk);
    oldsize = block->endptr - (char *) pointer;
}
else
{
    block = MemoryChunkGetBlock(chunk);
    oldsize = MemoryChunkGetSize(chunk);
}

Here the ExternalChunkGetBlock() macro is just subtracting the
ALLOC_BLOCKHDRSZ from the chunk pointer to obtain the block pointer,
whereas MemoryChunkGetBlock() is subtracting the blockoffset as is
stored in the 30-bits of the chunk header.

Andres and I had a conversation off-list about the storage of freelist
pointers.  Currently I have these stored in the actual allocated
memory.  The minimum allocation size is 8-bytes, which is big enough
for storing sizeof(void *). Andres suggested that it might be safer to
store this link at the end of the chunk rather than at the start.
I've not quite done that in the attached, but doing this should just
be a matter of adjusting the GetFreeListLink() macro to add the
chunksize - sizeof(AllocFreelistLink).

I did a little bit of benchmarking of the attached with a scale 1 pgbench.

master = 0b039e3a8

master
drowley@amd3990x:~$ pgbench -c 156 -j 156 -T 60 -S postgres
tps = 1638436.367793 (without initial connection time)
tps = 1652688.009579 (without initial connection time)
tps = 1671281.281856 (without initial connection time)

master + v2 patch
drowley@amd3990x:~$ pgbench -c 156 -j 156 -T 60 -S postgres
tps = 1825346.734486 (without initial connection time)
tps = 1824539.294142 (without initial connection time)
tps = 1807359.758822 (without initial connection time)

~10% faster.

There are a couple of things to note that might require discussion:

1. I've added a new restriction that block sizes cannot be above 1GB.
This is because the 30-bits in the MemoryChunk used for storing the
offset between the chunk and the block wouldn't be able to store the
offset if the chunk was offset more than 1GB from the block. I used
debian code search to see if I could find any user code that used
blocks this big. I found nothing.
2. slab.c has a new restriction that the chunk size cannot be >= 1GB.
I'm not at all concerned about this. I think if someone needed chunks
that big there'd be no benefits from slab context over an aset
context.
3. As mentioned above, aset.c now stores freelist pointers in the
allocated chunk's memory.  This allows us to get the header down to 8
bytes instead of today's 16 bytes. There's an increased danger that
buggy code that writes to memory after a pfree could stomp on this.

I think the patch is now starting to take shape.  I've added it to the
September commitfest [1].

David

[1] https://commitfest.postgresql.org/39/3810/

Attachments:

v2-0001-Improve-performance-of-and-reduce-overheads-of-me.patch (text/plain, 93.3K) download From 13034cd62f47eb26aca717e0c65a21f8c976477e Mon Sep 17 00:00:00 2001 From: David Rowley <dgrowley@gmail.com> Date: Thu, 9 Jun 2022 20:09:22 +1200 Subject: [PATCH v2] Improve performance of and reduce overheads of memory management Whenever we palloc a chunk of memory, traditionally, we prefix the returned pointer with a pointer to the memory context to which the chunk belongs. This is required so that we're able to easily determine the owning context when performing operations such as pfree() and repalloc(). For the AllocSet context, prior to this commit we additionally prefixed the pointer to the owning context with the size of the chunk. This made the header 16 bytes in size. This 16-byte overhead was required for all AllocSet allocations regardless of the allocation size. For the generation context, the problem was worse; in addition to the pointer to the owning context and chunk size, we also stored a pointer to the owning block so that we could track the number of freed chunks on a block. The slab allocator had a 16-byte chunk header. The changes being made here reduce the chunk header size down to just 8 bytes for all 3 of our memory context types. For small to medium sized allocations, this significantly increases the number of chunks that we can fit on a given block which results in much more efficient use of memory. Additionally, this commit completely changes the rule that pointers must be directly prefixed by the owning memory context and instead, we now insist that they're directly prefixed by an 8-byte value where the least significant 3-bits are set to a value to indicate which type of memory context the pointer belongs to. Using those 3 bits as an index to a new array which stores the methods for each memory context type, we're now able to pass the pointer given to functions such as pfree and repalloc to the function specific to that context implementation to allow them to devise their own methods of finding the memory context which owns the given allocated chunk of memory. The reason we're able to reduce the chunk header down to just 8 bytes is because of the way we make use of the remaining 61 bits of the required 8-byte chunk header. Here we also implement a general-purpose MemoryChunk struct which makes use of those 61 remaining bits to store the size of the chunk and the number of bytes which must be subtracted from the chunk to get a reference to the block that the chunk is stored on. We reserve 30 bits each for these fields and the 1 additional remaining bit is used to mark chunks with a chunk size larger than the value we can store in 30 bits (1GB). All 3 of our memory context types now use MemoryChunk as a chunk header. With this MemoryChunk, each of our 3 memory context types can quickly obtain a reference to the block any given chunk is located on. AllocSet is able to find the context to which the chunk is owned by first obtaining a reference to the block and then referencing the block's 'aset' field. Generation contexts did not have such a field in the GenerationBlock, so one is added in this commit. For allocations of 1GB or more, both AllocSet and the generation memory context types always allocate these on dedicated blocks. Since we cannot store the chunk size for these in the given 30 bits, we use the remaining 1 bit in the chunk header to mark such chunks as "external". Here external means the memory context implementation itself must be able to determine the size of the chunk and the block to which the chunk belongs. For AllocSet and generation contexts this is easy information to obtain as these larger chunks are always on dedicated blocks, finding the block is just a matter of subtracting the size of the block header from the chunk pointer. We obtain the size of the chunk just by subtracting the size of the block header from the size of the block which we already know the size of by way of the block's endptr. For the slab allocator, this commit adds a new restriction that slab chunks cannot be >= 1GB in size. If there happened to be any users of slab.c which used chunk sizes this large, they really should be using AllocSet instead. We also add a restriction that block sizes for all 3 of the memory allocators cannot be 1GB or larger. We would be unable to store the number of bytes that the block is offset from the chunk stored beyond this 1GB boundary on any block that was larger than 1GB. --- src/backend/utils/mmgr/README | 60 ++- src/backend/utils/mmgr/aset.c | 451 ++++++++++++----------- src/backend/utils/mmgr/generation.c | 326 ++++++++-------- src/backend/utils/mmgr/mcxt.c | 90 ++++- src/backend/utils/mmgr/slab.c | 190 ++++------ src/include/nodes/memnodes.h | 7 +- src/include/utils/memutils.h | 48 +-- src/include/utils/memutils_internal.h | 117 ++++++ src/include/utils/memutils_memorychunk.h | 185 ++++++++++ 9 files changed, 913 insertions(+), 561 deletions(-) create mode 100644 src/include/utils/memutils_internal.h create mode 100644 src/include/utils/memutils_memorychunk.h diff --git a/src/backend/utils/mmgr/README b/src/backend/utils/mmgr/README index 221b4bd343..2c98e92b69 100644 --- a/src/backend/utils/mmgr/README +++ b/src/backend/utils/mmgr/README @@ -378,35 +378,55 @@ MemoryContext like the parent and child contexts, and the name of the context. This is essentially an abstract superclass, and the behavior is -determined by the "methods" pointer is its virtual function table -(struct MemoryContextMethods). Specific memory context types will use -derived structs having these fields as their first fields. All the +determined by the "methods" pointer which references which set of +MemoryContextMethods are to be used. Specific memory context types will +use derived structs having these fields as their first fields. All the contexts of a specific type will have methods pointers that point to -the same static table of function pointers. +the corresponding element in the mcxt_methods[] array as defined in mcxt.c. While operations like allocating from and resetting a context take the relevant MemoryContext as a parameter, operations like free and realloc are trickier. To make those work, we require all memory context types to produce allocated chunks that are immediately, -without any padding, preceded by a pointer to the corresponding -MemoryContext. +without any padding, preceded by a uint64 value of which the least +significant 3 bits are set to the owning context's MemoryContextMethodID. +This allows the code to determine the correct MemoryContextMethods to +use by looking up the mcxt_methods[] array using the 3 bits as an index +into that array. If a type of allocator needs additional information about its chunks, like e.g. the size of the allocation, that information can in turn -precede the MemoryContext. This means the only overhead implied by -the memory context mechanism is a pointer to its context, so we're not -constraining context-type designers very much. - -Given this, routines like pfree determine their corresponding context -with an operation like (although that is usually encapsulated in -GetMemoryChunkContext()) - - MemoryContext context = *(MemoryContext*) (((char *) pointer) - sizeof(void *)); - -and then invoke the corresponding method for the context - - context->methods->free_p(pointer); - +either be encoded into the remaining 61 bits of the preceding uint64 value +or if more space is required, additional values may be stored directly prior +to the uint64 value. It is up to the context implementation to manage this. + +Given this, routines like pfree can determine which set of +MemoryContextMethods to call the free_p function for by calling +GetMemoryChunkMethodID() and finding the corresponding MemoryContextMethods +in the mcxt_methods array[]. For convenience, the MCXT_METHOD() macro is +provided, making the code as simple as: + +void +pfree(void *pointer) +{ + MCXT_METHOD(pointer, free_p)(pointer); +} + +All of the current memory contexts make use of the MemoryChunk header type +which is defined in memutils_memorychunk.h. This suits all of the existing +context types well as it makes use of the remaining 61-bits of the uint64 +header to efficiently encode the size of the chunk of memory and the number of +bytes which must be subtracted from the chunk in order to obtain a reference +to the block that the chunk belongs to. 30 bits are used for each of these. +If more than 30 bits are required (i.e. > 1GB) then the memory context must +manage that itself. This can be done by calling the +MemoryChunkSetHdrMaskExternal() function on the given chunk. Currently, each +memory context type stores large allocations on dedicated blocks (which always +contain only a single chunk). For these, finding the block is simple as we +know that the chunk must be the first on the given block, so the block is +always at a fixed offset to the chunk. For these, finding the size of the +chunk is also simple as the block always stores an endptr which we can use to +calculate the size of the chunk. More Control Over aset.c Behavior --------------------------------- diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index ec3e264a73..f052deee8a 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -49,6 +49,8 @@ #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" /*-------------------- * Chunk freelist k holds chunks of size 1 << (k + ALLOC_MINBITS), @@ -66,7 +68,9 @@ * CAUTION: ALLOC_MINBITS must be large enough so that * 1<<ALLOC_MINBITS is at least MAXALIGN, * or we may fail to align the smallest chunks adequately. - * 8-byte alignment is enough on all currently known machines. + * 8-byte alignment is enough on all currently known machines. This 8-byte + * minimum also allows us to store a pointer to the next freelist item within + * the chunk of memory itself. * * With the current parameters, request sizes up to 8K are treated as chunks, * larger requests go into dedicated blocks. Change ALLOCSET_NUM_FREELISTS @@ -98,10 +102,9 @@ */ #define ALLOC_BLOCKHDRSZ MAXALIGN(sizeof(AllocBlockData)) -#define ALLOC_CHUNKHDRSZ sizeof(struct AllocChunkData) +#define ALLOC_CHUNKHDRSZ sizeof(MemoryChunk) typedef struct AllocBlockData *AllocBlock; /* forward reference */ -typedef struct AllocChunkData *AllocChunk; /* * AllocPointer @@ -109,6 +112,25 @@ typedef struct AllocChunkData *AllocChunk; */ typedef void *AllocPointer; +/* + * AllocFreelistLink + * When pfreeing memory, if we maintain a freelist for the given chunk's + * size then we use a AllocFreelistLink to point to the current item in + * the AllocSetContext's freelist and then set the given freelist element + * to point to the chunk being freed. + */ +typedef struct AllocFreelistLink +{ + MemoryChunk *next; +} AllocFreelistLink; + +/* + * Obtain a AllocFreelistLink for the given chunk. Allocation sizes are + * always at least sizeof(AllocFreelistLink), so we reuse the pointer's memory + * itself to store the freelist link + */ +#define GetFreeListLink(c, sz) ((AllocFreelistLink *) ((char *) (c) + ALLOC_CHUNKHDRSZ)) + /* * AllocSetContext is our standard implementation of MemoryContext. * @@ -123,7 +145,7 @@ typedef struct AllocSetContext MemoryContextData header; /* Standard memory-context fields */ /* Info about storage allocated in this context: */ AllocBlock blocks; /* head of list of blocks in this set */ - AllocChunk freelist[ALLOCSET_NUM_FREELISTS]; /* free chunk lists */ + MemoryChunk *freelist[ALLOCSET_NUM_FREELISTS]; /* free chunk lists */ /* Allocation parameters for this context: */ Size initBlockSize; /* initial block size */ Size maxBlockSize; /* maximum block size */ @@ -139,8 +161,8 @@ typedef AllocSetContext *AllocSet; /* * AllocBlock * An AllocBlock is the unit of memory that is obtained by aset.c - * from malloc(). It contains one or more AllocChunks, which are - * the units requested by palloc() and freed by pfree(). AllocChunks + * from malloc(). It contains one or more MemoryChunks, which are + * the units requested by palloc() and freed by pfree(). MemoryChunks * cannot be returned to malloc() individually, instead they are put * on freelists by pfree() and re-used by the next palloc() that has * a matching request size. @@ -158,48 +180,12 @@ typedef struct AllocBlockData } AllocBlockData; /* - * AllocChunk - * The prefix of each piece of memory in an AllocBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "aset" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). We simplify matters for this - * module by requiring sizeof(AllocChunkData) to be maxaligned, and then - * we can ensure things work by adding any required alignment padding before - * the "aset" field. There is a static assertion below that the alignment - * is done correctly. - */ -typedef struct AllocChunkData -{ - /* size is always the size of the usable space in the chunk */ - Size size; -#ifdef MEMORY_CONTEXT_CHECKING - /* when debugging memory usage, also store actual requested size */ - /* this is zero in a free chunk */ - Size requested_size; - -#define ALLOCCHUNK_RAWSIZE (SIZEOF_SIZE_T * 2 + SIZEOF_VOID_P) -#else -#define ALLOCCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P) -#endif /* MEMORY_CONTEXT_CHECKING */ - - /* ensure proper alignment by adding padding if needed */ -#if (ALLOCCHUNK_RAWSIZE % MAXIMUM_ALIGNOF) != 0 - char padding[MAXIMUM_ALIGNOF - ALLOCCHUNK_RAWSIZE % MAXIMUM_ALIGNOF]; -#endif - - /* aset is the owning aset if allocated, or the freelist link if free */ - void *aset; - /* there must not be any padding to reach a MAXALIGN boundary here! */ -} AllocChunkData; - -/* - * Only the "aset" field should be accessed outside this module. + * Only the "hdrmask" field should be accessed outside this module. * We keep the rest of an allocated chunk's header marked NOACCESS when using * valgrind. But note that chunk headers that are in a freelist are kept * accessible, for simplicity. */ -#define ALLOCCHUNK_PRIVATE_LEN offsetof(AllocChunkData, aset) +#define ALLOCCHUNK_PRIVATE_LEN offsetof(MemoryChunk, hdrmask) /* * AllocPointerIsValid @@ -213,10 +199,12 @@ typedef struct AllocChunkData */ #define AllocSetIsValid(set) PointerIsValid(set) -#define AllocPointerGetChunk(ptr) \ - ((AllocChunk)(((char *)(ptr)) - ALLOC_CHUNKHDRSZ)) -#define AllocChunkGetPointer(chk) \ - ((AllocPointer)(((char *)(chk)) + ALLOC_CHUNKHDRSZ)) +/* + * We always store external chunks on a dedicated block. This makes fetching + * the block from an external chunk easy since it's always the first and only + * chunk on the block. + */ +#define ExternalChunkGetBlock(chunk) (AllocBlock) ((char *) chunk - ALLOC_BLOCKHDRSZ) /* * Rather than repeatedly creating and deleting memory contexts, we keep some @@ -260,42 +248,6 @@ static AllocSetFreeList context_freelists[2] = } }; -/* - * These functions implement the MemoryContext API for AllocSet contexts. - */ -static void *AllocSetAlloc(MemoryContext context, Size size); -static void AllocSetFree(MemoryContext context, void *pointer); -static void *AllocSetRealloc(MemoryContext context, void *pointer, Size size); -static void AllocSetReset(MemoryContext context); -static void AllocSetDelete(MemoryContext context); -static Size AllocSetGetChunkSpace(MemoryContext context, void *pointer); -static bool AllocSetIsEmpty(MemoryContext context); -static void AllocSetStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); - -#ifdef MEMORY_CONTEXT_CHECKING -static void AllocSetCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for AllocSet contexts. - */ -static const MemoryContextMethods AllocSetMethods = { - AllocSetAlloc, - AllocSetFree, - AllocSetRealloc, - AllocSetReset, - AllocSetDelete, - AllocSetGetChunkSpace, - AllocSetIsEmpty, - AllocSetStats -#ifdef MEMORY_CONTEXT_CHECKING - ,AllocSetCheck -#endif -}; - /* ---------- * AllocSetFreeIndex - @@ -387,18 +339,20 @@ AllocSetContextCreateInternal(MemoryContext parent, AllocSet set; AllocBlock block; - /* Assert we padded AllocChunkData properly */ + /* Assert we padded MemoryChunk properly */ StaticAssertStmt(ALLOC_CHUNKHDRSZ == MAXALIGN(ALLOC_CHUNKHDRSZ), - "sizeof(AllocChunkData) is not maxaligned"); - StaticAssertStmt(offsetof(AllocChunkData, aset) + sizeof(MemoryContext) == - ALLOC_CHUNKHDRSZ, - "padding calculation in AllocChunkData is wrong"); + "sizeof(MemoryChunk) is not maxaligned"); /* * First, validate allocation parameters. Once these were regular runtime * test and elog's, but in practice Asserts seem sufficient because nobody * varies their parameters at runtime. We somewhat arbitrarily enforce a - * minimum 1K block size. + * minimum 1K block size. We restrict the maximum block size to + * MEMORYCHUNK_MAX_SIZE as MemoryChunks are limited to this in regards to + * addressing the offset between the chunk and the block that the chunk is + * stored on. We would be unable to store the offset between the chunk + * and block for any chunks that were beyond MEMORYCHUNK_MAX_SIZE bytes + * into the block if the block was to be larger than this. */ Assert(initBlockSize == MAXALIGN(initBlockSize) && initBlockSize >= 1024); @@ -409,6 +363,7 @@ AllocSetContextCreateInternal(MemoryContext parent, (minContextSize == MAXALIGN(minContextSize) && minContextSize >= 1024 && minContextSize <= maxBlockSize)); + Assert(maxBlockSize <= MEMORYCHUNK_MAX_SIZE); /* * Check whether the parameters match either available freelist. We do @@ -443,7 +398,7 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Reinitialize its header, installing correct name and parent */ MemoryContextCreate((MemoryContext) set, T_AllocSetContext, - &AllocSetMethods, + MCTX_ASET_ID, parent, name); @@ -519,7 +474,8 @@ AllocSetContextCreateInternal(MemoryContext parent, * * We have to have allocChunkLimit a power of two, because the requested * and actually-allocated sizes of any chunk must be on the same side of - * the limit, else we get confused about whether the chunk is "big". + * the limit, else we get confused about whether the chunk is on a + * dedicated block. * * Also, allocChunkLimit must not exceed ALLOCSET_SEPARATE_THRESHOLD. */ @@ -534,7 +490,7 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) set, T_AllocSetContext, - &AllocSetMethods, + MCTX_ASET_ID, parent, name); @@ -555,7 +511,7 @@ AllocSetContextCreateInternal(MemoryContext parent, * thrash malloc() when a context is repeatedly reset after small allocations, * which is typical behavior for per-tuple contexts. */ -static void +void AllocSetReset(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -623,7 +579,7 @@ AllocSetReset(MemoryContext context) * * Unlike AllocSetReset, this *must* free all resources of the set. */ -static void +void AllocSetDelete(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -717,12 +673,12 @@ AllocSetDelete(MemoryContext context) * is marked, as mcxt.c will set it to UNDEFINED. In some paths we will * return space that is marked NOACCESS - AllocSetRealloc has to beware! */ -static void * +void * AllocSetAlloc(MemoryContext context, Size size) { AllocSet set = (AllocSet) context; AllocBlock block; - AllocChunk chunk; + MemoryChunk *chunk; int fidx; Size chunk_size; Size blksize; @@ -746,18 +702,20 @@ AllocSetAlloc(MemoryContext context, Size size) block->aset = set; block->freeptr = block->endptr = ((char *) block) + blksize; - chunk = (AllocChunk) (((char *) block) + ALLOC_BLOCKHDRSZ); - chunk->aset = set; - chunk->size = chunk_size; + chunk = (MemoryChunk *) (((char *) block) + ALLOC_BLOCKHDRSZ); + + /* mark the MemoryChunk as externally managed */ + MemoryChunkSetHdrMaskExternal(chunk, MCTX_ASET_ID); + #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk_size) - set_sentinel(AllocChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* @@ -780,13 +738,13 @@ AllocSetAlloc(MemoryContext context, Size size) } /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -799,31 +757,37 @@ AllocSetAlloc(MemoryContext context, Size size) chunk = set->freelist[fidx]; if (chunk != NULL) { - Assert(chunk->size >= size); + AllocFreelistLink *link; - set->freelist[fidx] = (AllocChunk) chunk->aset; + Assert(MemoryChunkGetSize(chunk) >= size); - chunk->aset = (void *) set; + chunk_size = (1 << ALLOC_MINBITS) << fidx; + link = GetFreeListLink(chunk, chunk_size); + + /* pop this chunk off the freelist */ + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + set->freelist[fidx] = link->next; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(AllocChunkGetPointer(chunk), size); + if (size < MemoryChunkGetSize(chunk)) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, - chunk->size - size); + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, + MemoryChunkGetSize(chunk) - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -856,6 +820,7 @@ AllocSetAlloc(MemoryContext context, Size size) */ while (availspace >= ((1 << ALLOC_MINBITS) + ALLOC_CHUNKHDRSZ)) { + AllocFreelistLink *link; Size availchunk = availspace - ALLOC_CHUNKHDRSZ; int a_fidx = AllocSetFreeIndex(availchunk); @@ -871,22 +836,26 @@ AllocSetAlloc(MemoryContext context, Size size) availchunk = ((Size) 1 << (a_fidx + ALLOC_MINBITS)); } - chunk = (AllocChunk) (block->freeptr); + chunk = (MemoryChunk *) (block->freeptr); /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, ALLOC_CHUNKHDRSZ); - block->freeptr += (availchunk + ALLOC_CHUNKHDRSZ); availspace -= (availchunk + ALLOC_CHUNKHDRSZ); - chunk->size = availchunk; + MemoryChunkSetHdrMask(chunk, block, availchunk, MCTX_ASET_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = 0; /* mark it free */ #endif - chunk->aset = (void *) set->freelist[a_fidx]; + /* push this chunk onto the freelist */ + link = GetFreeListLink(chunk, availspace); + + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + link->next = set->freelist[a_fidx]; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); + set->freelist[a_fidx] = chunk; } - /* Mark that we need to create a new block */ block = NULL; } @@ -954,7 +923,7 @@ AllocSetAlloc(MemoryContext context, Size size) /* * OK, do the allocation */ - chunk = (AllocChunk) (block->freeptr); + chunk = (MemoryChunk *) (block->freeptr); /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, ALLOC_CHUNKHDRSZ); @@ -962,67 +931,66 @@ AllocSetAlloc(MemoryContext context, Size size) block->freeptr += (chunk_size + ALLOC_CHUNKHDRSZ); Assert(block->freeptr <= block->endptr); - chunk->aset = (void *) set; - chunk->size = chunk_size; + MemoryChunkSetHdrMask(chunk, block, chunk_size, MCTX_ASET_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(AllocChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * AllocSetFree * Frees allocated memory; memory is removed from the set. */ -static void -AllocSetFree(MemoryContext context, void *pointer) +void +AllocSetFree(void *pointer) { - AllocSet set = (AllocSet) context; - AllocChunk chunk = AllocPointerGetChunk(pointer); + AllocSet set; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); + if (MemoryChunkIsExternal(chunk)) + { + + AllocBlock block = ExternalChunkGetBlock(chunk); + + set = block->aset; + #ifdef MEMORY_CONTEXT_CHECKING - /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunk->size) - if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", - set->header.name, chunk); + { + Size chunk_size = block->endptr - (char *) pointer; + + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < chunk_size) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); + } #endif - if (chunk->size > set->allocChunkLimit) - { - /* - * Big chunks are certain to have been allocated as single-chunk - * blocks. Just unlink that block and return it to malloc(). - */ - AllocBlock block = (AllocBlock) (((char *) chunk) - ALLOC_BLOCKHDRSZ); /* - * Try to verify that we have a sane block pointer: it should - * reference the correct aset, and freeptr and endptr should point - * just past the chunk. + * Try to verify that we have a sane block pointer, the freeptr should + * match the endptr. */ - if (block->aset != set || - block->freeptr != block->endptr || - block->freeptr != ((char *) block) + - (chunk->size + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) + if (block->freeptr != block->endptr) elog(ERROR, "could not find block containing chunk %p", chunk); /* OK, remove block from aset's list and free it */ @@ -1033,7 +1001,7 @@ AllocSetFree(MemoryContext context, void *pointer) if (block->next) block->next->prev = block->prev; - context->mem_allocated -= block->endptr - ((char *) block); + set->header.mem_allocated -= block->endptr - ((char *) block); #ifdef CLOBBER_FREED_MEMORY wipe_mem(block, block->freeptr - ((char *) block)); @@ -1042,20 +1010,37 @@ AllocSetFree(MemoryContext context, void *pointer) } else { - /* Normal case, put the chunk into appropriate freelist */ - int fidx = AllocSetFreeIndex(chunk->size); + AllocBlock block = MemoryChunkGetBlock(chunk); + Size chunk_size = MemoryChunkGetSize(chunk); + AllocFreelistLink *link = GetFreeListLink(chunk, chunksize); + int fidx; - chunk->aset = (void *) set->freelist[fidx]; + set = block->aset; + +#ifdef MEMORY_CONTEXT_CHECKING + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < chunk_size) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); +#endif #ifdef CLOBBER_FREED_MEMORY - wipe_mem(pointer, chunk->size); + wipe_mem(pointer, chunk_size); #endif + /* Normal case, put the chunk into appropriate freelist */ + fidx = AllocSetFreeIndex(chunk_size); + + /* push this chunk onto the top of the freelist for this chunk size */ + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + link->next = set->freelist[fidx]; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); + set->freelist[fidx] = chunk; #ifdef MEMORY_CONTEXT_CHECKING /* Reset requested_size to 0 in chunks that are on freelist */ chunk->requested_size = 0; #endif - set->freelist[fidx] = chunk; } } @@ -1071,17 +1056,28 @@ AllocSetFree(MemoryContext context, void *pointer) * (In principle, we could use VALGRIND_GET_VBITS() to rediscover the old * request size.) */ -static void * -AllocSetRealloc(MemoryContext context, void *pointer, Size size) +void * +AllocSetRealloc(void *pointer, Size size) { - AllocSet set = (AllocSet) context; - AllocChunk chunk = AllocPointerGetChunk(pointer); + AllocBlock block; + AllocSet set; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); Size oldsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - oldsize = chunk->size; + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); + oldsize = block->endptr - (char *) pointer; + } + else + { + block = MemoryChunkGetBlock(chunk); + oldsize = MemoryChunkGetSize(chunk); + } + set = block->aset; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ @@ -1091,37 +1087,25 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) set->header.name, chunk); #endif - if (oldsize > set->allocChunkLimit) + if (MemoryChunkIsExternal(chunk)) { /* * The chunk must have been allocated as a single-chunk block. Use * realloc() to make the containing block bigger, or smaller, with * minimum space wastage. */ - AllocBlock block = (AllocBlock) (((char *) chunk) - ALLOC_BLOCKHDRSZ); Size chksize; Size blksize; Size oldblksize; /* - * Try to verify that we have a sane block pointer: it should - * reference the correct aset, and freeptr and endptr should point - * just past the chunk. + * Try to verify that we have a sane block pointer, the freeptr should + * match the endptr. */ - if (block->aset != set || - block->freeptr != block->endptr || - block->freeptr != ((char *) block) + - (oldsize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) + if (block->freeptr != block->endptr) elog(ERROR, "could not find block containing chunk %p", chunk); - /* - * Even if the new request is less than set->allocChunkLimit, we stick - * with the single-chunk block approach. Therefore we need - * chunk->size to be bigger than set->allocChunkLimit, so we don't get - * confused about the chunk's status in future calls. - */ - chksize = Max(size, set->allocChunkLimit + 1); - chksize = MAXALIGN(chksize); + chksize = MAXALIGN(size); /* Do the realloc */ blksize = chksize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ; @@ -1136,21 +1120,20 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) } /* updated separately, not to underflow when (oldblksize > blksize) */ - context->mem_allocated -= oldblksize; - context->mem_allocated += blksize; + set->header.mem_allocated -= oldblksize; + set->header.mem_allocated += blksize; block->freeptr = block->endptr = ((char *) block) + blksize; /* Update pointers since block has likely been moved */ - chunk = (AllocChunk) (((char *) block) + ALLOC_BLOCKHDRSZ); - pointer = AllocChunkGetPointer(chunk); + chunk = (MemoryChunk *) (((char *) block) + ALLOC_BLOCKHDRSZ); + pointer = MemoryChunkGetPointer(chunk); if (block->prev) block->prev->next = block; else set->blocks = block; if (block->next) block->next->prev = block; - chunk->size = chksize; #ifdef MEMORY_CONTEXT_CHECKING #ifdef RANDOMIZE_ALLOCATED_MEMORY @@ -1172,9 +1155,8 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) #endif chunk->requested_size = size; - /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) + if (size < chksize) set_sentinel(pointer, size); #else /* !MEMORY_CONTEXT_CHECKING */ @@ -1289,34 +1271,58 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) memcpy(newPointer, pointer, oldsize); /* free old chunk */ - AllocSetFree((MemoryContext) set, pointer); + AllocSetFree(pointer); return newPointer; } } +/* + * AllocSetGetChunkContext + * Return the MemoryContext that 'pointer' belongs to. + */ +MemoryContext +AllocSetGetChunkContext(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + AllocBlock block; + AllocSet set; + + if (MemoryChunkIsExternal(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (AllocBlock) MemoryChunkGetBlock(chunk); + + set = block->aset; + + return &set->header; +} + /* * AllocSetGetChunkSpace * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -AllocSetGetChunkSpace(MemoryContext context, void *pointer) +Size +AllocSetGetChunkSpace(void *pointer) { - AllocChunk chunk = AllocPointerGetChunk(pointer); - Size result; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); - VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - result = chunk->size + ALLOC_CHUNKHDRSZ; - VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return result; + if (MemoryChunkIsExternal(chunk)) + { + AllocBlock block = ExternalChunkGetBlock(chunk); + + return block->endptr - (char *) chunk; + } + + return MemoryChunkGetSize(chunk) + ALLOC_CHUNKHDRSZ; } /* * AllocSetIsEmpty * Is an allocset empty of any allocated space? */ -static bool +bool AllocSetIsEmpty(MemoryContext context) { /* @@ -1339,7 +1345,7 @@ AllocSetIsEmpty(MemoryContext context) * totals: if not NULL, add stats about this context into *totals. * print_to_stderr: print stats to stderr if true, elog otherwise. */ -static void +void AllocSetStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr) @@ -1363,13 +1369,21 @@ AllocSetStats(MemoryContext context, } for (fidx = 0; fidx < ALLOCSET_NUM_FREELISTS; fidx++) { - AllocChunk chunk; + MemoryChunk *chunk = set->freelist[fidx]; - for (chunk = set->freelist[fidx]; chunk != NULL; - chunk = (AllocChunk) chunk->aset) + while (chunk != NULL) { + Size chksz = MemoryChunkGetSize(chunk); + AllocFreelistLink *link = GetFreeListLink(chunk, chksz); + + Assert(((1 << ALLOC_MINBITS) << fidx) == chksz); + freechunks++; - freespace += chunk->size + ALLOC_CHUNKHDRSZ; + freespace += chksz + ALLOC_CHUNKHDRSZ; + + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + chunk = link->next; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); } } @@ -1404,7 +1418,7 @@ AllocSetStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void AllocSetCheck(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -1421,6 +1435,7 @@ AllocSetCheck(MemoryContext context) long blk_used = block->freeptr - bpoz; long blk_data = 0; long nchunks = 0; + bool has_external_chunk = false; if (set->keeper == block) total_allocated += block->endptr - ((char *) set); @@ -1452,14 +1467,25 @@ AllocSetCheck(MemoryContext context) */ while (bpoz < block->freeptr) { - AllocChunk chunk = (AllocChunk) bpoz; + MemoryChunk *chunk = (MemoryChunk *) bpoz; + AllocBlock chunkblock; Size chsize, dsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - chsize = chunk->size; /* aligned chunk size */ + if (MemoryChunkIsExternal(chunk)) + { + chsize = block->endptr - (char *) MemoryChunkGetPointer(chunk); /* aligned chunk size */ + chunkblock = ExternalChunkGetBlock(chunk); + has_external_chunk = true; + } + else + { + chsize = MemoryChunkGetSize(chunk); /* aligned chunk size */ + chunkblock = (AllocBlock) MemoryChunkGetBlock(chunk); + } dsize = chunk->requested_size; /* real data */ /* @@ -1478,20 +1504,15 @@ AllocSetCheck(MemoryContext context) elog(WARNING, "problem in alloc set %s: bad single-chunk %p in block %p", name, chunk, block); - /* - * If chunk is allocated, check for correct aset pointer. (If it's - * free, the aset is the freelist pointer, which we can't check as - * easily...) Note this is an incomplete test, since palloc(0) - * produces an allocated chunk with requested_size == 0. - */ - if (dsize > 0 && chunk->aset != (void *) set) - elog(WARNING, "problem in alloc set %s: bogus aset link in block %p, chunk %p", - name, block, chunk); + /* Check the block offset correctly matches this block */ + if (block != chunkblock) + elog(WARNING, "problem in alloc set %s: bad block offset for chunk %p in block %p", + name, chunk, block); /* * Check for overwrite of padding space in an allocated chunk. */ - if (chunk->aset == (void *) set && dsize < chsize && + if (dsize > 0 && dsize < chsize && !sentinel_ok(chunk, ALLOC_CHUNKHDRSZ + dsize)) elog(WARNING, "problem in alloc set %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); @@ -1500,7 +1521,7 @@ AllocSetCheck(MemoryContext context) * If chunk is allocated, disallow external access to private part * of chunk header. */ - if (chunk->aset == (void *) set) + if (dsize > 0) VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); blk_data += chsize; @@ -1512,6 +1533,10 @@ AllocSetCheck(MemoryContext context) if ((blk_data + (nchunks * ALLOC_CHUNKHDRSZ)) != blk_used) elog(WARNING, "problem in alloc set %s: found inconsistent memory block %p", name, block); + + if (has_external_chunk && nchunks > 1) + elog(WARNING, "problem in alloc set %s: external chunk on non-dedicated block %p", + name, block); } Assert(total_allocated == context->mem_allocated); diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index e530e272e0..02709c4bf6 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -39,15 +39,16 @@ #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" #define Generation_BLOCKHDRSZ MAXALIGN(sizeof(GenerationBlock)) -#define Generation_CHUNKHDRSZ sizeof(GenerationChunk) +#define Generation_CHUNKHDRSZ sizeof(MemoryChunk) #define Generation_CHUNK_FRACTION 8 typedef struct GenerationBlock GenerationBlock; /* forward reference */ -typedef struct GenerationChunk GenerationChunk; typedef void *GenerationPointer; @@ -89,6 +90,7 @@ typedef struct GenerationContext struct GenerationBlock { dlist_node node; /* doubly-linked list of blocks */ + GenerationContext *context; /* pointer back to the owning context */ Size blksize; /* allocated size of this block */ int nchunks; /* number of chunks in the block */ int nfree; /* number of free chunks */ @@ -97,104 +99,36 @@ struct GenerationBlock }; /* - * GenerationChunk - * The prefix of each piece of memory in a GenerationBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "context" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). We simplify matters for this - * module by requiring sizeof(GenerationChunk) to be maxaligned, and then - * we can ensure things work by adding any required alignment padding before - * the pointer fields. There is a static assertion below that the alignment - * is done correctly. - */ -struct GenerationChunk -{ - /* size is always the size of the usable space in the chunk */ - Size size; -#ifdef MEMORY_CONTEXT_CHECKING - /* when debugging memory usage, also store actual requested size */ - /* this is zero in a free chunk */ - Size requested_size; - -#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T * 2 + SIZEOF_VOID_P * 2) -#else -#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P * 2) -#endif /* MEMORY_CONTEXT_CHECKING */ - - /* ensure proper alignment by adding padding if needed */ -#if (GENERATIONCHUNK_RAWSIZE % MAXIMUM_ALIGNOF) != 0 - char padding[MAXIMUM_ALIGNOF - GENERATIONCHUNK_RAWSIZE % MAXIMUM_ALIGNOF]; -#endif - - GenerationBlock *block; /* block owning this chunk */ - GenerationContext *context; /* owning context, or NULL if freed chunk */ - /* there must not be any padding to reach a MAXALIGN boundary here! */ -}; - -/* - * Only the "context" field should be accessed outside this module. + * Only the "hdrmask" field should be accessed outside this module. * We keep the rest of an allocated chunk's header marked NOACCESS when using * valgrind. But note that freed chunk headers are kept accessible, for * simplicity. */ -#define GENERATIONCHUNK_PRIVATE_LEN offsetof(GenerationChunk, context) - +#define GENERATIONCHUNK_PRIVATE_LEN offsetof(MemoryChunk, hdrmask) /* * GenerationIsValid * True iff set is valid allocation set. */ #define GenerationIsValid(set) PointerIsValid(set) -#define GenerationPointerGetChunk(ptr) \ - ((GenerationChunk *)(((char *)(ptr)) - Generation_CHUNKHDRSZ)) -#define GenerationChunkGetPointer(chk) \ - ((GenerationPointer *)(((char *)(chk)) + Generation_CHUNKHDRSZ)) +/* + * We always store external chunks on a dedicated block. This makes fetching + * the block from an external chunk easy since it's always the first and only + * chunk on the block. + */ +#define ExternalChunkGetBlock(chunk) \ + (GenerationBlock *) ((char *) chunk - Generation_BLOCKHDRSZ) /* Inlined helper functions */ -static inline void GenerationBlockInit(GenerationBlock *block, Size blksize); +static inline void GenerationBlockInit(GenerationContext *context, + GenerationBlock *block, + Size blksize); static inline bool GenerationBlockIsEmpty(GenerationBlock *block); static inline void GenerationBlockMarkEmpty(GenerationBlock *block); static inline Size GenerationBlockFreeBytes(GenerationBlock *block); static inline void GenerationBlockFree(GenerationContext *set, GenerationBlock *block); -/* - * These functions implement the MemoryContext API for Generation contexts. - */ -static void *GenerationAlloc(MemoryContext context, Size size); -static void GenerationFree(MemoryContext context, void *pointer); -static void *GenerationRealloc(MemoryContext context, void *pointer, Size size); -static void GenerationReset(MemoryContext context); -static void GenerationDelete(MemoryContext context); -static Size GenerationGetChunkSpace(MemoryContext context, void *pointer); -static bool GenerationIsEmpty(MemoryContext context); -static void GenerationStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); - -#ifdef MEMORY_CONTEXT_CHECKING -static void GenerationCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for Generation contexts. - */ -static const MemoryContextMethods GenerationMethods = { - GenerationAlloc, - GenerationFree, - GenerationRealloc, - GenerationReset, - GenerationDelete, - GenerationGetChunkSpace, - GenerationIsEmpty, - GenerationStats -#ifdef MEMORY_CONTEXT_CHECKING - ,GenerationCheck -#endif -}; - /* * Public routines @@ -225,15 +159,17 @@ GenerationContextCreate(MemoryContext parent, /* Assert we padded GenerationChunk properly */ StaticAssertStmt(Generation_CHUNKHDRSZ == MAXALIGN(Generation_CHUNKHDRSZ), - "sizeof(GenerationChunk) is not maxaligned"); - StaticAssertStmt(offsetof(GenerationChunk, context) + sizeof(MemoryContext) == - Generation_CHUNKHDRSZ, - "padding calculation in GenerationChunk is wrong"); + "sizeof(MemoryChunk) is not maxaligned"); /* * First, validate allocation parameters. Asserts seem sufficient because * nobody varies their parameters at runtime. We somewhat arbitrarily - * enforce a minimum 1K block size. + * enforce a minimum 1K block size. We restrict the maximum block size to + * MEMORYCHUNK_MAX_SIZE as MemoryChunks are limited to this in regards to + * addressing the offset between the chunk and the block that the chunk is + * stored on. We would be unable to store the offset between the chunk + * and block for any chunks that were beyond MEMORYCHUNK_MAX_SIZE bytes + * into the block if the block was to be larger than this. */ Assert(initBlockSize == MAXALIGN(initBlockSize) && initBlockSize >= 1024); @@ -244,6 +180,7 @@ GenerationContextCreate(MemoryContext parent, (minContextSize == MAXALIGN(minContextSize) && minContextSize >= 1024 && minContextSize <= maxBlockSize)); + Assert(maxBlockSize <= MEMORYCHUNK_MAX_SIZE); /* Determine size of initial block */ allocSize = MAXALIGN(sizeof(GenerationContext)) + @@ -278,7 +215,7 @@ GenerationContextCreate(MemoryContext parent, block = (GenerationBlock *) (((char *) set) + MAXALIGN(sizeof(GenerationContext))); /* determine the block size and initialize it */ firstBlockSize = allocSize - MAXALIGN(sizeof(GenerationContext)); - GenerationBlockInit(block, firstBlockSize); + GenerationBlockInit(set, block, firstBlockSize); /* add it to the doubly-linked list of blocks */ dlist_push_head(&set->blocks, &block->node); @@ -310,7 +247,7 @@ GenerationContextCreate(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) set, T_GenerationContext, - &GenerationMethods, + MCTX_GENERATION_ID, parent, name); @@ -326,7 +263,7 @@ GenerationContextCreate(MemoryContext parent, * The code simply frees all the blocks in the context - we don't keep any * keeper blocks or anything like that. */ -static void +void GenerationReset(MemoryContext context) { GenerationContext *set = (GenerationContext *) context; @@ -371,7 +308,7 @@ GenerationReset(MemoryContext context) * GenerationDelete * Free all memory which is allocated in the given context. */ -static void +void GenerationDelete(MemoryContext context) { /* Reset to release all releasable GenerationBlocks */ @@ -393,12 +330,12 @@ GenerationDelete(MemoryContext context) * is marked, as mcxt.c will set it to UNDEFINED. In some paths we will * return space that is marked NOACCESS - GenerationRealloc has to beware! */ -static void * +void * GenerationAlloc(MemoryContext context, Size size) { GenerationContext *set = (GenerationContext *) context; GenerationBlock *block; - GenerationChunk *chunk; + MemoryChunk *chunk; Size chunk_size = MAXALIGN(size); Size required_size = chunk_size + Generation_CHUNKHDRSZ; @@ -414,6 +351,7 @@ GenerationAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; /* block with a single (used) chunk */ + block->context = set; block->blksize = blksize; block->nchunks = 1; block->nfree = 0; @@ -421,33 +359,33 @@ GenerationAlloc(MemoryContext context, Size size) /* the block is completely full */ block->freeptr = block->endptr = ((char *) block) + blksize; - chunk = (GenerationChunk *) (((char *) block) + Generation_BLOCKHDRSZ); - chunk->block = block; - chunk->context = set; - chunk->size = chunk_size; + chunk = (MemoryChunk *) (((char *) block) + Generation_BLOCKHDRSZ); + + /* mark the MemoryChunk as externally managed */ + MemoryChunkSetHdrMaskExternal(chunk, MCTX_GENERATION_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk_size) - set_sentinel(GenerationChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) GenerationChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* add the block to the list of allocated blocks */ dlist_push_head(&set->blocks, &block->node); /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) GenerationChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return GenerationChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -516,7 +454,7 @@ GenerationAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; /* initialize the new block */ - GenerationBlockInit(block, blksize); + GenerationBlockInit(set, block, blksize); /* add it to the doubly-linked list of blocks */ dlist_push_head(&set->blocks, &block->node); @@ -533,7 +471,7 @@ GenerationAlloc(MemoryContext context, Size size) Assert(block != NULL); Assert((block->endptr - block->freeptr) >= Generation_CHUNKHDRSZ + chunk_size); - chunk = (GenerationChunk *) block->freeptr; + chunk = (MemoryChunk *) block->freeptr; /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, Generation_CHUNKHDRSZ); @@ -543,29 +481,26 @@ GenerationAlloc(MemoryContext context, Size size) Assert(block->freeptr <= block->endptr); - chunk->block = block; - chunk->context = set; - chunk->size = chunk_size; - + MemoryChunkSetHdrMask(chunk, block, chunk_size, MCTX_GENERATION_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(GenerationChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) GenerationChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) GenerationChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return GenerationChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -574,8 +509,10 @@ GenerationAlloc(MemoryContext context, Size size) * mem_allocated field. */ static inline void -GenerationBlockInit(GenerationBlock *block, Size blksize) +GenerationBlockInit(GenerationContext *context, GenerationBlock *block, + Size blksize) { + block->context = context; block->blksize = blksize; block->nchunks = 0; block->nfree = 0; @@ -661,33 +598,48 @@ GenerationBlockFree(GenerationContext *set, GenerationBlock *block) * Update number of chunks in the block, and if all chunks in the block * are now free then discard the block. */ -static void -GenerationFree(MemoryContext context, void *pointer) +void +GenerationFree(void *pointer) { - GenerationContext *set = (GenerationContext *) context; - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); GenerationBlock *block; + GenerationContext *set; +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + Size chunksize; +#endif + + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + chunksize = block->endptr - (char *) pointer; +#endif + } + else + { + block = MemoryChunkGetBlock(chunk); +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + chunksize = MemoryChunkGetSize(chunk); +#endif + } /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - block = chunk->block; + set = block->context; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunk->size) + if (chunk->requested_size < chunksize) if (!sentinel_ok(pointer, chunk->requested_size)) elog(WARNING, "detected write past chunk end in %s %p", ((MemoryContext) set)->name, chunk); #endif #ifdef CLOBBER_FREED_MEMORY - wipe_mem(pointer, chunk->size); + wipe_mem(pointer, chunksize); #endif - /* Reset context to NULL in freed chunks */ - chunk->context = NULL; - #ifdef MEMORY_CONTEXT_CHECKING /* Reset requested_size to 0 in freed chunks */ chunk->requested_size = 0; @@ -732,7 +684,7 @@ GenerationFree(MemoryContext context, void *pointer) */ dlist_delete(&block->node); - context->mem_allocated -= block->blksize; + set->header.mem_allocated -= block->blksize; free(block); } @@ -742,18 +694,30 @@ GenerationFree(MemoryContext context, void *pointer) * and discard the old one. The only exception is when the new size fits * into the old chunk - in that case we just update chunk header. */ -static void * -GenerationRealloc(MemoryContext context, void *pointer, Size size) +void * +GenerationRealloc(void *pointer, Size size) { - GenerationContext *set = (GenerationContext *) context; - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationContext *set; + GenerationBlock *block; GenerationPointer newPointer; Size oldsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - oldsize = chunk->size; + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); + oldsize = block->endptr - (char *) pointer; + } + else + { + block = MemoryChunkGetBlock(chunk); + oldsize = MemoryChunkGetSize(chunk); + } + + set = block->context; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ @@ -848,7 +812,7 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) memcpy(newPointer, pointer, oldsize); /* free old chunk */ - GenerationFree((MemoryContext) set, pointer); + GenerationFree(pointer); return newPointer; } @@ -858,23 +822,51 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -GenerationGetChunkSpace(MemoryContext context, void *pointer) +MemoryContext +GenerationGetChunkContext(void *pointer) { - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); - Size result; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationBlock *block; - VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - result = chunk->size + Generation_CHUNKHDRSZ; - VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return result; + if (MemoryChunkIsExternal(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (GenerationBlock *) MemoryChunkGetBlock(chunk); + + return &block->context->header; +} + +/* + * GenerationGetChunkSpace + * Given a currently-allocated chunk, determine the total space + * it occupies (including all memory-allocation overhead). + */ +Size +GenerationGetChunkSpace(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationBlock *block; + Size chunksize; + + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); + chunksize = block->endptr - (char *) pointer; + } + else + { + block = MemoryChunkGetBlock(chunk); + chunksize = MemoryChunkGetSize(chunk); + } + + return Generation_CHUNKHDRSZ + chunksize; } /* * GenerationIsEmpty * Is a GenerationContext empty of any allocated space? */ -static bool +bool GenerationIsEmpty(MemoryContext context) { GenerationContext *set = (GenerationContext *) context; @@ -903,7 +895,7 @@ GenerationIsEmpty(MemoryContext context) * XXX freespace only accounts for empty space at the end of the block, not * space of freed chunks (which is unknown). */ -static void +void GenerationStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr) @@ -961,7 +953,7 @@ GenerationStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void GenerationCheck(MemoryContext context) { GenerationContext *gen = (GenerationContext *) context; @@ -976,6 +968,7 @@ GenerationCheck(MemoryContext context) int nfree, nchunks; char *ptr; + bool has_external_chunk = false; total_allocated += block->blksize; @@ -987,6 +980,11 @@ GenerationCheck(MemoryContext context) elog(WARNING, "problem in Generation %s: number of free chunks %d in block %p exceeds %d allocated", name, block->nfree, block, block->nchunks); + /* check block belongs to the correct context */ + if (block->context != gen) + elog(WARNING, "problem in Generation %s: bogus context link in block %p", + name, block); + /* Now walk through the chunks and count them. */ nfree = 0; nchunks = 0; @@ -994,42 +992,47 @@ GenerationCheck(MemoryContext context) while (ptr < block->freeptr) { - GenerationChunk *chunk = (GenerationChunk *) ptr; + MemoryChunk *chunk = (MemoryChunk *) ptr; + GenerationBlock *chunkblock; + Size chunksize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); + if (MemoryChunkIsExternal(chunk)) + { + chunkblock = ExternalChunkGetBlock(chunk); + chunksize = block->endptr - (char *) MemoryChunkGetPointer(chunk); + has_external_chunk = true; + } + else + { + chunkblock = MemoryChunkGetBlock(chunk); + chunksize = MemoryChunkGetSize(chunk); + } + /* move to the next chunk */ - ptr += (chunk->size + Generation_CHUNKHDRSZ); + ptr += (chunksize + Generation_CHUNKHDRSZ); nchunks += 1; /* chunks have both block and context pointers, so check both */ - if (chunk->block != block) + if (chunkblock != block) elog(WARNING, "problem in Generation %s: bogus block link in block %p, chunk %p", name, block, chunk); - /* - * Check for valid context pointer. Note this is an incomplete - * test, since palloc(0) produces an allocated chunk with - * requested_size == 0. - */ - if ((chunk->requested_size > 0 && chunk->context != gen) || - (chunk->context != gen && chunk->context != NULL)) - elog(WARNING, "problem in Generation %s: bogus context link in block %p, chunk %p", - name, block, chunk); /* now make sure the chunk size is correct */ - if (chunk->size < chunk->requested_size || - chunk->size != MAXALIGN(chunk->size)) + if (chunksize < chunk->requested_size || + chunksize != MAXALIGN(chunksize)) elog(WARNING, "problem in Generation %s: bogus chunk size in block %p, chunk %p", name, block, chunk); /* is chunk allocated? */ - if (chunk->context != NULL) + if (chunk->requested_size > 0) { - /* check sentinel, but only in allocated blocks */ - if (chunk->requested_size < chunk->size && + /* check sentinel */ + if (chunk->requested_size < chunksize && !sentinel_ok(chunk, Generation_CHUNKHDRSZ + chunk->requested_size)) elog(WARNING, "problem in Generation %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); @@ -1041,7 +1044,7 @@ GenerationCheck(MemoryContext context) * If chunk is allocated, disallow external access to private part * of chunk header. */ - if (chunk->context != NULL) + if (chunk->requested_size > 0) VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); } @@ -1056,6 +1059,11 @@ GenerationCheck(MemoryContext context) if (nfree != block->nfree) elog(WARNING, "problem in Generation %s: number of free chunks %d in block %p does not match header %d", name, nfree, block, block->nfree); + + if (has_external_chunk && nchunks > 1) + elog(WARNING, "problem in Generation %s: external chunk on non-dedicated block %p", + name, block); + } Assert(total_allocated == context->mem_allocated); diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index e12be1b9bd..7f9514c450 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -29,12 +29,60 @@ #include "utils/fmgrprotos.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_internal.h" /***************************************************************************** * GLOBAL MEMORY * *****************************************************************************/ +static const MemoryContextMethods mcxt_methods[] = { + [MCTX_ASET_ID] = { + AllocSetAlloc, + AllocSetFree, + AllocSetRealloc, + AllocSetReset, + AllocSetDelete, + AllocSetGetChunkContext, + AllocSetGetChunkSpace, + AllocSetIsEmpty, + AllocSetStats +#ifdef MEMORY_CONTEXT_CHECKING + ,AllocSetCheck +#endif + }, + + [MCTX_GENERATION_ID] = { + GenerationAlloc, + GenerationFree, + GenerationRealloc, + GenerationReset, + GenerationDelete, + GenerationGetChunkContext, + GenerationGetChunkSpace, + GenerationIsEmpty, + GenerationStats +#ifdef MEMORY_CONTEXT_CHECKING + ,GenerationCheck +#endif + }, + + [MCTX_SLAB_ID] = { + SlabAlloc, + SlabFree, + SlabRealloc, + SlabReset, + SlabDelete, + SlabGetChunkContext, + SlabGetChunkSpace, + SlabIsEmpty, + SlabStats +#ifdef MEMORY_CONTEXT_CHECKING + ,SlabCheck +#endif + }, +}; + /* * CurrentMemoryContext * Default memory context for allocations. @@ -73,6 +121,13 @@ static void MemoryContextStatsPrint(MemoryContext context, void *passthru, #define AssertNotInCriticalSection(context) \ Assert(CritSectionCount == 0 || (context)->allowInCritSection) +/* + * Call the given function in the MemoryContextMethods for the memory context + * type that 'pointer' belongs to. + */ +#define MCXT_METHOD(pointer, method) \ + mcxt_methods[GetMemoryChunkMethodID(pointer)].method + /***************************************************************************** * EXPORTED ROUTINES * @@ -422,6 +477,17 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) context->allowInCritSection = allow; } +/* + * GetMemoryChunkContext + * Given a currently-allocated chunk, determine the MemoryContext that + * the chunk belongs to. + */ +MemoryContext +GetMemoryChunkContext(void *pointer) +{ + return MCXT_METHOD(pointer, get_chunk_context) (pointer); +} + /* * GetMemoryChunkSpace * Given a currently-allocated chunk, determine the total space @@ -433,9 +499,7 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) Size GetMemoryChunkSpace(void *pointer) { - MemoryContext context = GetMemoryChunkContext(pointer); - - return context->methods->get_chunk_space(context, pointer); + return MCXT_METHOD(pointer, get_chunk_space) (pointer); } /* @@ -814,7 +878,7 @@ MemoryContextContains(MemoryContext context, void *pointer) void MemoryContextCreate(MemoryContext node, NodeTag tag, - const MemoryContextMethods *methods, + MemoryContextMethodID method_id, MemoryContext parent, const char *name) { @@ -824,7 +888,7 @@ MemoryContextCreate(MemoryContext node, /* Initialize all standard fields of memory context header */ node->type = tag; node->isReset = true; - node->methods = methods; + node->methods = &mcxt_methods[method_id]; node->parent = parent; node->firstchild = NULL; node->mem_allocated = 0; @@ -1174,9 +1238,11 @@ palloc_extended(Size size, int flags) void pfree(void *pointer) { +#ifdef USE_VALGRIND MemoryContext context = GetMemoryChunkContext(pointer); +#endif - context->methods->free_p(context, pointer); + MCXT_METHOD(pointer, free_p) (pointer); VALGRIND_MEMPOOL_FREE(context, pointer); } @@ -1187,7 +1253,9 @@ pfree(void *pointer) void * repalloc(void *pointer, Size size) { +#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND) MemoryContext context = GetMemoryChunkContext(pointer); +#endif void *ret; if (!AllocSizeIsValid(size)) @@ -1198,9 +1266,11 @@ repalloc(void *pointer, Size size) /* isReset must be false already */ Assert(!context->isReset); - ret = context->methods->realloc(context, pointer, size); + ret = MCXT_METHOD(pointer, realloc) (pointer, size); if (unlikely(ret == NULL)) { + MemoryContext context = GetMemoryChunkContext(pointer); + MemoryContextStats(TopMemoryContext); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), @@ -1257,7 +1327,9 @@ MemoryContextAllocHuge(MemoryContext context, Size size) void * repalloc_huge(void *pointer, Size size) { +#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND) MemoryContext context = GetMemoryChunkContext(pointer); +#endif void *ret; if (!AllocHugeSizeIsValid(size)) @@ -1268,9 +1340,11 @@ repalloc_huge(void *pointer, Size size) /* isReset must be false already */ Assert(!context->isReset); - ret = context->methods->realloc(context, pointer, size); + ret = MCXT_METHOD(pointer, realloc) (pointer, size); if (unlikely(ret == NULL)) { + MemoryContext context = GetMemoryChunkContext(pointer); + MemoryContextStats(TopMemoryContext); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), diff --git a/src/backend/utils/mmgr/slab.c b/src/backend/utils/mmgr/slab.c index 67d97b22e5..77f9e12049 100644 --- a/src/backend/utils/mmgr/slab.c +++ b/src/backend/utils/mmgr/slab.c @@ -55,6 +55,8 @@ #include "lib/ilist.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" /* * SlabContext is a specialized implementation of MemoryContext. @@ -90,75 +92,23 @@ typedef struct SlabBlock dlist_node node; /* doubly-linked list */ int nfree; /* number of free chunks */ int firstFreeChunk; /* index of the first free chunk in the block */ -} SlabBlock; - -/* - * SlabChunk - * The prefix of each piece of memory in a SlabBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "slab" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). Since we support no machines on - * which MAXALIGN is more than twice sizeof(void *), this happens without any - * special hacking in this struct declaration. But there is a static - * assertion below that the alignment is done correctly. - */ -typedef struct SlabChunk -{ - SlabBlock *block; /* block owning this chunk */ SlabContext *slab; /* owning context */ - /* there must not be any padding to reach a MAXALIGN boundary here! */ -} SlabChunk; +} SlabBlock; +#define Slab_CHUNKHDRSZ sizeof(MemoryChunk) #define SlabPointerGetChunk(ptr) \ - ((SlabChunk *)(((char *)(ptr)) - sizeof(SlabChunk))) + ((MemoryChunk *)(((char *)(ptr)) - sizeof(MemoryChunk))) #define SlabChunkGetPointer(chk) \ - ((void *)(((char *)(chk)) + sizeof(SlabChunk))) + ((void *)(((char *)(chk)) + sizeof(MemoryChunk))) #define SlabBlockGetChunk(slab, block, idx) \ - ((SlabChunk *) ((char *) (block) + sizeof(SlabBlock) \ + ((MemoryChunk *) ((char *) (block) + sizeof(SlabBlock) \ + (idx * slab->fullChunkSize))) #define SlabBlockStart(block) \ ((char *) block + sizeof(SlabBlock)) #define SlabChunkIndex(slab, block, chunk) \ (((char *) chunk - SlabBlockStart(block)) / slab->fullChunkSize) -/* - * These functions implement the MemoryContext API for Slab contexts. - */ -static void *SlabAlloc(MemoryContext context, Size size); -static void SlabFree(MemoryContext context, void *pointer); -static void *SlabRealloc(MemoryContext context, void *pointer, Size size); -static void SlabReset(MemoryContext context); -static void SlabDelete(MemoryContext context); -static Size SlabGetChunkSpace(MemoryContext context, void *pointer); -static bool SlabIsEmpty(MemoryContext context); -static void SlabStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); -#ifdef MEMORY_CONTEXT_CHECKING -static void SlabCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for Slab contexts. - */ -static const MemoryContextMethods SlabMethods = { - SlabAlloc, - SlabFree, - SlabRealloc, - SlabReset, - SlabDelete, - SlabGetChunkSpace, - SlabIsEmpty, - SlabStats -#ifdef MEMORY_CONTEXT_CHECKING - ,SlabCheck -#endif -}; - - /* * SlabContextCreate * Create a new Slab context. @@ -168,8 +118,7 @@ static const MemoryContextMethods SlabMethods = { * blockSize: allocation block size * chunkSize: allocation chunk size * - * The chunkSize may not exceed: - * MAXALIGN_DOWN(SIZE_MAX) - MAXALIGN(sizeof(SlabBlock)) - sizeof(SlabChunk) + * The chunkSize may not exceed MEMORYCHUNK_MAX_SIZE */ MemoryContext SlabContextCreate(MemoryContext parent, @@ -184,19 +133,14 @@ SlabContextCreate(MemoryContext parent, SlabContext *slab; int i; - /* Assert we padded SlabChunk properly */ - StaticAssertStmt(sizeof(SlabChunk) == MAXALIGN(sizeof(SlabChunk)), - "sizeof(SlabChunk) is not maxaligned"); - StaticAssertStmt(offsetof(SlabChunk, slab) + sizeof(MemoryContext) == - sizeof(SlabChunk), - "padding calculation in SlabChunk is wrong"); + Assert(chunkSize <= MEMORYCHUNK_MAX_SIZE); /* Make sure the linked list node fits inside a freed chunk */ if (chunkSize < sizeof(int)) chunkSize = sizeof(int); /* chunk, including SLAB header (both addresses nicely aligned) */ - fullChunkSize = sizeof(SlabChunk) + MAXALIGN(chunkSize); + fullChunkSize = Slab_CHUNKHDRSZ + MAXALIGN(chunkSize); /* Make sure the block can store at least one chunk. */ if (blockSize < fullChunkSize + sizeof(SlabBlock)) @@ -265,7 +209,7 @@ SlabContextCreate(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) slab, T_SlabContext, - &SlabMethods, + MCTX_SLAB_ID, parent, name); @@ -279,7 +223,7 @@ SlabContextCreate(MemoryContext parent, * The code simply frees all the blocks in the context - we don't keep any * keeper blocks or anything like that. */ -static void +void SlabReset(MemoryContext context) { int i; @@ -322,7 +266,7 @@ SlabReset(MemoryContext context) * SlabDelete * Free all memory which is allocated in the given context. */ -static void +void SlabDelete(MemoryContext context) { /* Reset to release all the SlabBlocks */ @@ -336,12 +280,12 @@ SlabDelete(MemoryContext context) * Returns pointer to allocated memory of given size or NULL if * request could not be completed; memory is added to the slab. */ -static void * +void * SlabAlloc(MemoryContext context, Size size) { SlabContext *slab = castNode(SlabContext, context); SlabBlock *block; - SlabChunk *chunk; + MemoryChunk *chunk; int idx; Assert(slab); @@ -370,6 +314,7 @@ SlabAlloc(MemoryContext context, Size size) block->nfree = slab->chunksPerBlock; block->firstFreeChunk = 0; + block->slab = slab; /* * Put all the chunks on a freelist. Walk the chunks and point each @@ -378,7 +323,7 @@ SlabAlloc(MemoryContext context, Size size) for (idx = 0; idx < slab->chunksPerBlock; idx++) { chunk = SlabBlockGetChunk(slab, block, idx); - *(int32 *) SlabChunkGetPointer(chunk) = (idx + 1); + *(int32 *) MemoryChunkGetPointer(chunk) = (idx + 1); } /* @@ -426,8 +371,8 @@ SlabAlloc(MemoryContext context, Size size) * Remove the chunk from the freelist head. The index of the next free * chunk is stored in the chunk itself. */ - VALGRIND_MAKE_MEM_DEFINED(SlabChunkGetPointer(chunk), sizeof(int32)); - block->firstFreeChunk = *(int32 *) SlabChunkGetPointer(chunk); + VALGRIND_MAKE_MEM_DEFINED(MemoryChunkGetPointer(chunk), sizeof(int32)); + block->firstFreeChunk = *(int32 *) MemoryChunkGetPointer(chunk); Assert(block->firstFreeChunk >= 0); Assert(block->firstFreeChunk <= slab->chunksPerBlock); @@ -464,47 +409,47 @@ SlabAlloc(MemoryContext context, Size size) slab->minFreeChunks = 0; /* Prepare to initialize the chunk header. */ - VALGRIND_MAKE_MEM_UNDEFINED(chunk, sizeof(SlabChunk)); - - chunk->block = block; - chunk->slab = slab; + VALGRIND_MAKE_MEM_UNDEFINED(chunk, Slab_CHUNKHDRSZ); + MemoryChunkSetHdrMask(chunk, block, MAXALIGN(slab->chunkSize), + MCTX_SLAB_ID); #ifdef MEMORY_CONTEXT_CHECKING /* slab mark to catch clobber of "unused" space */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) { - set_sentinel(SlabChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); VALGRIND_MAKE_MEM_NOACCESS(((char *) chunk) + - sizeof(SlabChunk) + slab->chunkSize, + Slab_CHUNKHDRSZ + slab->chunkSize, slab->fullChunkSize - - (slab->chunkSize + sizeof(SlabChunk))); + (slab->chunkSize + Slab_CHUNKHDRSZ)); } #endif + #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) SlabChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif Assert(slab->nblocks * slab->blockSize == context->mem_allocated); - return SlabChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * SlabFree * Frees allocated memory; memory is removed from the slab. */ -static void -SlabFree(MemoryContext context, void *pointer) +void +SlabFree(void *pointer) { int idx; - SlabContext *slab = castNode(SlabContext, context); - SlabChunk *chunk = SlabPointerGetChunk(pointer); - SlabBlock *block = chunk->block; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) if (!sentinel_ok(pointer, slab->chunkSize)) elog(WARNING, "detected write past chunk end in %s %p", slab->header.name, chunk); @@ -560,13 +505,13 @@ SlabFree(MemoryContext context, void *pointer) { free(block); slab->nblocks--; - context->mem_allocated -= slab->blockSize; + slab->header.mem_allocated -= slab->blockSize; } else dlist_push_head(&slab->freelist[block->nfree], &block->node); Assert(slab->nblocks >= 0); - Assert(slab->nblocks * slab->blockSize == context->mem_allocated); + Assert(slab->nblocks * slab->blockSize == slab->header.mem_allocated); } /* @@ -582,13 +527,14 @@ SlabFree(MemoryContext context, void *pointer) * rather pointless - Slab is meant for chunks of constant size, and moreover * realloc is usually used to enlarge the chunk. */ -static void * -SlabRealloc(MemoryContext context, void *pointer, Size size) +void * +SlabRealloc(void *pointer, Size size) { - SlabContext *slab = castNode(SlabContext, context); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; Assert(slab); - /* can't do actual realloc with slab, but let's try to be gentle */ if (size == slab->chunkSize) return pointer; @@ -597,15 +543,33 @@ SlabRealloc(MemoryContext context, void *pointer, Size size) return NULL; /* keep compiler quiet */ } +/* + * SlabGetChunkContext + * Return the MemoryContext that 'pointer' belongs to. + */ +MemoryContext +SlabGetChunkContext(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; + + Assert(slab != NULL); + + return &slab->header; +} + /* * SlabGetChunkSpace * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -SlabGetChunkSpace(MemoryContext context, void *pointer) +Size +SlabGetChunkSpace(void *pointer) { - SlabContext *slab = castNode(SlabContext, context); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; Assert(slab); @@ -616,7 +580,7 @@ SlabGetChunkSpace(MemoryContext context, void *pointer) * SlabIsEmpty * Is an Slab empty of any allocated space? */ -static bool +bool SlabIsEmpty(MemoryContext context) { SlabContext *slab = castNode(SlabContext, context); @@ -635,7 +599,7 @@ SlabIsEmpty(MemoryContext context) * totals: if not NULL, add stats about this context into *totals. * print_to_stderr: print stats to stderr if true, elog otherwise. */ -static void +void SlabStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, @@ -697,7 +661,7 @@ SlabStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void SlabCheck(MemoryContext context) { int i; @@ -742,7 +706,7 @@ SlabCheck(MemoryContext context) nfree = 0; while (idx < slab->chunksPerBlock) { - SlabChunk *chunk; + MemoryChunk *chunk; /* count the chunk as free, add it to the bitmap */ nfree++; @@ -750,8 +714,8 @@ SlabCheck(MemoryContext context) /* read index of the next free chunk */ chunk = SlabBlockGetChunk(slab, block, idx); - VALGRIND_MAKE_MEM_DEFINED(SlabChunkGetPointer(chunk), sizeof(int32)); - idx = *(int32 *) SlabChunkGetPointer(chunk); + VALGRIND_MAKE_MEM_DEFINED(MemoryChunkGetPointer(chunk), sizeof(int32)); + idx = *(int32 *) MemoryChunkGetPointer(chunk); } for (j = 0; j < slab->chunksPerBlock; j++) @@ -759,19 +723,23 @@ SlabCheck(MemoryContext context) /* non-zero bit in the bitmap means chunk the chunk is used */ if (!slab->freechunks[j]) { - SlabChunk *chunk = SlabBlockGetChunk(slab, block, j); - - /* chunks have both block and slab pointers, so check both */ - if (chunk->block != block) + MemoryChunk *chunk = SlabBlockGetChunk(slab, block, j); + SlabBlock *chunkblock = (SlabBlock *) MemoryChunkGetBlock(chunk); + + /* + * check the chunk's blockoffset correctly points back to + * the block + */ + if (chunkblock != block) elog(WARNING, "problem in slab %s: bogus block link in block %p, chunk %p", name, block, chunk); - if (chunk->slab != slab) + if (block->slab != slab) elog(WARNING, "problem in slab %s: bogus slab link in block %p, chunk %p", name, block, chunk); /* there might be sentinel (thanks to alignment) */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) if (!sentinel_ok(chunk, slab->chunkSize)) elog(WARNING, "problem in slab %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); diff --git a/src/include/nodes/memnodes.h b/src/include/nodes/memnodes.h index 16cd56da6d..63d07358cd 100644 --- a/src/include/nodes/memnodes.h +++ b/src/include/nodes/memnodes.h @@ -59,11 +59,12 @@ typedef struct MemoryContextMethods { void *(*alloc) (MemoryContext context, Size size); /* call this free_p in case someone #define's free() */ - void (*free_p) (MemoryContext context, void *pointer); - void *(*realloc) (MemoryContext context, void *pointer, Size size); + void (*free_p) (void *pointer); + void *(*realloc) (void *pointer, Size size); void (*reset) (MemoryContext context); void (*delete_context) (MemoryContext context); - Size (*get_chunk_space) (MemoryContext context, void *pointer); + MemoryContext (*get_chunk_context) (void *pointer); + Size (*get_chunk_space) (void *pointer); bool (*is_empty) (MemoryContext context); void (*stats) (MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, diff --git a/src/include/utils/memutils.h b/src/include/utils/memutils.h index 495d1af201..244f7bf4ff 100644 --- a/src/include/utils/memutils.h +++ b/src/include/utils/memutils.h @@ -79,6 +79,7 @@ extern void MemoryContextDeleteChildren(MemoryContext context); extern void MemoryContextSetIdentifier(MemoryContext context, const char *id); extern void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent); +extern MemoryContext GetMemoryChunkContext(void *pointer); extern Size GetMemoryChunkSpace(void *pointer); extern MemoryContext MemoryContextGetParent(MemoryContext context); extern bool MemoryContextIsEmpty(MemoryContext context); @@ -98,53 +99,6 @@ extern bool MemoryContextContains(MemoryContext context, void *pointer); #define MemoryContextCopyAndSetIdentifier(cxt, id) \ MemoryContextSetIdentifier(cxt, MemoryContextStrdup(cxt, id)) -/* - * GetMemoryChunkContext - * Given a currently-allocated chunk, determine the context - * it belongs to. - * - * All chunks allocated by any memory context manager are required to be - * preceded by the corresponding MemoryContext stored, without padding, in the - * preceding sizeof(void*) bytes. A currently-allocated chunk must contain a - * backpointer to its owning context. The backpointer is used by pfree() and - * repalloc() to find the context to call. - */ -#ifndef FRONTEND -static inline MemoryContext -GetMemoryChunkContext(void *pointer) -{ - MemoryContext context; - - /* - * Try to detect bogus pointers handed to us, poorly though we can. - * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an - * allocated chunk. - */ - Assert(pointer != NULL); - Assert(pointer == (void *) MAXALIGN(pointer)); - - /* - * OK, it's probably safe to look at the context. - */ - context = *(MemoryContext *) (((char *) pointer) - sizeof(void *)); - - AssertArg(MemoryContextIsValid(context)); - - return context; -} -#endif - -/* - * This routine handles the context-type-independent part of memory - * context creation. It's intended to be called from context-type- - * specific creation routines, and noplace else. - */ -extern void MemoryContextCreate(MemoryContext node, - NodeTag tag, - const MemoryContextMethods *methods, - MemoryContext parent, - const char *name); - extern void HandleLogMemoryContextInterrupt(void); extern void ProcessLogMemoryContextInterrupt(void); diff --git a/src/include/utils/memutils_internal.h b/src/include/utils/memutils_internal.h new file mode 100644 index 0000000000..2dcfdd7ec3 --- /dev/null +++ b/src/include/utils/memutils_internal.h @@ -0,0 +1,117 @@ +/*------------------------------------------------------------------------- + * + * memutils_internal.h + * This file contains declarations for memory allocation utility + * functions for internal use. + * + * + * Portions Copyright (c) 2022, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/utils/memutils_internal.h + * + *------------------------------------------------------------------------- + */ + +#ifndef MEMUTILS_INTERNAL_H +#define MEMUTILS_INTERNAL_H + +#include "utils/memutils.h" + +extern void *AllocSetAlloc(MemoryContext context, Size size); +extern void AllocSetFree(void *pointer); +extern void *AllocSetRealloc(void *pointer, Size size); +extern void AllocSetReset(MemoryContext context); +extern void AllocSetDelete(MemoryContext context); +extern MemoryContext AllocSetGetChunkContext(void *pointer); +extern Size AllocSetGetChunkSpace(void *pointer); +extern bool AllocSetIsEmpty(MemoryContext context); +extern void AllocSetStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); + +#ifdef MEMORY_CONTEXT_CHECKING +extern void AllocSetCheck(MemoryContext context); +#endif + + +extern void *GenerationAlloc(MemoryContext context, Size size); +extern void GenerationFree(void *pointer); +extern void *GenerationRealloc(void *pointer, Size size); +extern void GenerationReset(MemoryContext context); +extern void GenerationDelete(MemoryContext context); +extern MemoryContext GenerationGetChunkContext(void *pointer); +extern Size GenerationGetChunkSpace(void *pointer); +extern bool GenerationIsEmpty(MemoryContext context); +extern void GenerationStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); + +#ifdef MEMORY_CONTEXT_CHECKING +extern void GenerationCheck(MemoryContext context); +#endif + + +/* + * These functions implement the MemoryContext API for Slab contexts. + */ +extern void *SlabAlloc(MemoryContext context, Size size); +extern void SlabFree(void *pointer); +extern void *SlabRealloc(void *pointer, Size size); +extern void SlabReset(MemoryContext context); +extern void SlabDelete(MemoryContext context); +extern MemoryContext SlabGetChunkContext(void *pointer); +extern Size SlabGetChunkSpace(void *pointer); +extern bool SlabIsEmpty(MemoryContext context); +extern void SlabStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); +#ifdef MEMORY_CONTEXT_CHECKING +extern void SlabCheck(MemoryContext context); +#endif + +/* + * MemoryContextMethodID + * A unique identifier for each MemoryContext implementation which + * indicates the index into the mcxt_methods[] array. See mcxt.c. + */ +typedef enum MemoryContextMethodID +{ + MCTX_ASET_ID = 0, + MCTX_GENERATION_ID, + MCTX_SLAB_ID, +} MemoryContextMethodID; + +/* + * This routine handles the context-type-independent part of memory + * context creation. It's intended to be called from context-type- + * specific creation routines, and noplace else. + */ +extern void MemoryContextCreate(MemoryContext node, + NodeTag tag, + MemoryContextMethodID method_id, + MemoryContext parent, + const char *name); + +static inline MemoryContextMethodID +GetMemoryChunkMethodID(void *pointer) +{ + uint64 header; + + /* + * Try to detect bogus pointers handed to us, poorly though we can. + * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an + * allocated chunk. + */ + Assert(pointer != NULL); + Assert(pointer == (void *) MAXALIGN(pointer)); + + header = *((uint64 *) ((char *) pointer - sizeof(uint64))); + + return header & 7; +} + +#endif /* MEMUTILS_INTERNAL_H */ diff --git a/src/include/utils/memutils_memorychunk.h b/src/include/utils/memutils_memorychunk.h new file mode 100644 index 0000000000..6239cf9008 --- /dev/null +++ b/src/include/utils/memutils_memorychunk.h @@ -0,0 +1,185 @@ +/*------------------------------------------------------------------------- + * + * memutils_memorychunk.h + * Here we define a struct named MemoryChunk which implementations of + * MemoryContexts may use as a header for chunks of memory they allocate. + * + * A MemoryChunk provides a lightweight header which a MemoryContext can use + * to store the size of an allocation and a reference back to the block which + * the given chunk is allocated on. + * + * Although MemoryChunks are used by each of our MemoryContexts, other + * implementations may choose to implement their own method for storing chunk + * headers. The only requirement is that the header end with an 8-byte value + * which the least significant 3-bits of are set to the MemoryContextMethodID + * of the given context. + * + * By default, a MemoryChunk is 8 bytes in size, however when + * MEMORY_CONTEXT_CHECKING is defined the header becomes 16 bytes in size due + * to the additional requested_size field. The MemoryContext may use this + * field for whatever they wish, but it is intended to be used for additional + * checks which are only done in MEMORY_CONTEXT_CHECKING builds. + * + * The MemoryChunk contains a uint64 field named 'hdrmask'. This field is + * used to encode 4 separate pieces of information. Starting with the least + * significant bits of 'hdrmask', the bits of this field as used as follows: + * + * 1. 3-bits to indicate the MemoryContextMethodID + * 2. 1-bit to indicate if the chunk is externally managed (see below) + * 3. 30-bits for the amount of memory which was reserved for the chunk + * 4. 30-bits for the number of bytes that must be subtracted from the chunk + * to obtain the address of the block that the chunk is stored on. + * + * Because we're limited to a block offset and chunk size of 1GB (30-bits), + * any allocation which exceeds this amount must call MemoryChunkSetExternal() + * and the MemoryContext must devise its own method for storing the offset for + * the block and size of the chunk. + * + * Interface: + * + * MemoryChunkSetHdrMask: + * Used to set up a non-external MemoryChunk. + * + * MemoryChunkSetHdrMaskExternal: + * Used to set up an externally managed MemoryChunk. + * + * MemoryChunkIsExternal: + * Determine if the given MemoryChunk is externally managed, i.e. + * MemoryChunkSetHdrMaskExternal() was called on the chunk. + * + * MemoryChunkGetSize: + * For non-external chunks, return the size of the chunk as it was set + * in the call to MemoryChunkSetHdrMask. + * + * MemoryChunkGetBlock: + * For non-external chunks, return a pointer to the block as it was set + * in the call to MemoryChunkSetHdrMask. + * + * Also exports: + * MEMORYCHUNK_MAX_SIZE + * PointerGetMemoryChunk + * MemoryChunkGetPointer + * + * Portions Copyright (c) 2022, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/utils/memutils_memorychunk.h + * + *------------------------------------------------------------------------- + */ + +#ifndef MEMUTILS_MEMORYCHUNK_H +#define MEMUTILS_MEMORYCHUNK_H + +#include "utils/memutils_internal.h" + + /* + * The maximum size for a memory chunk before it must be externally managed. + */ +#define MEMORYCHUNK_MAX_SIZE 0x3FFFFFFF + + /* + * The value to AND onto the hdrmask to determine if it's an externally + * managed memory chunk. + */ +#define MEMORYCHUNK_EXTERNAL_BIT (1 << 3) + +typedef struct MemoryChunk +{ +#ifdef MEMORY_CONTEXT_CHECKING + Size requested_size; +#endif + + /* bitfield for storing details about the chunk */ + uint64 hdrmask; /* must be last */ +} MemoryChunk; + +/* Get the MemoryChunk from the pointer */ +#define PointerGetMemoryChunk(p) ((MemoryChunk *) ((char *) (p) - sizeof(MemoryChunk))) +/* Get the pointer from the MemoryChunk */ +#define MemoryChunkGetPointer(c) ((void *) ((char *) (c) + sizeof(MemoryChunk))) + +/* private macros for making the inline functions below more simple */ +#define HdrMaskIsExternal(hdrmask) ((hdrmask) & MEMORYCHUNK_EXTERNAL_BIT) +#define HdrMaskChunkSize(hdrmask) (((hdrmask) >> 4) & MEMORYCHUNK_MAX_SIZE) +#define HdrMaskBlockOffset(hdrmask) ((hdrmask) >> 34) + +/* + * MemoryChunkSetHdrMask + * Store the given 'block', 'chunk_size' and 'methodid' in the given + * MemoryChunk. + * + * The number of bytes between 'block' and 'chunk' must be <= + * MEMORYCHUNK_MAX_SIZE + */ +static inline void +MemoryChunkSetHdrMask(MemoryChunk *chunk, void *block, + Size chunk_size, MemoryContextMethodID methodid) +{ + Size blockoffset = (char *) chunk - (char *) block; + + Assert((char *) chunk > (char *) block); + Assert(blockoffset <= MEMORYCHUNK_MAX_SIZE); + Assert(chunk_size <= MEMORYCHUNK_MAX_SIZE); + Assert(methodid <= 7); + + chunk->hdrmask = (blockoffset << 34) | (chunk_size << 4) | methodid; +} + +/* + * MemoryChunkSetHdrMaskExternal + * Set 'chunk' as an externally managed chunk. Here we only record the + * MemoryContextMethodID and set the external chunk bit. + */ +static inline void +MemoryChunkSetHdrMaskExternal(MemoryChunk *chunk, + MemoryContextMethodID methodid) +{ + Assert(methodid <= 7); + + chunk->hdrmask = MEMORYCHUNK_EXTERNAL_BIT | methodid; +} + +/* + * MemoryChunkIsExternal + * Return true if 'chunk' is marked as external. + */ +static inline bool +MemoryChunkIsExternal(MemoryChunk *chunk) +{ + return HdrMaskIsExternal(chunk->hdrmask); +} + +/* + * MemoryChunkGetChunkSize + * For non-external chunks, returns the size of the chunk as was set + * in MemoryChunkSetHdrMask. + */ +static inline Size +MemoryChunkGetSize(MemoryChunk *chunk) +{ + Assert(!HdrMaskIsExternal(chunk->hdrmask)); + + return HdrMaskChunkSize(chunk->hdrmask); +} + +/* + * MemoryChunkGetBlock + * For non-external chunks, returns the pointer to the block as was set + * in MemoryChunkSetHdrMask. + */ +static inline void * +MemoryChunkGetBlock(MemoryChunk *chunk) +{ + Assert(!HdrMaskIsExternal(chunk->hdrmask)); + + return (void *) ((char *) chunk - HdrMaskBlockOffset(chunk->hdrmask)); +} + +/* cleanup all internal definitions */ +#undef MEMORYCHUNK_EXTERNAL_BIT +#undef HdrMaskIsExternal +#undef HdrMaskChunkSize +#undef HdrMaskBlockOffset + +#endif /* MEMUTILS_MEMORYCHUNK_H */ -- 2.34.1
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-09 14:36  Robert Haas <robertmhaas@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 2 replies; 152+ messages in thread

From: Robert Haas @ 2022-08-09 14:36 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, Aug 9, 2022 at 8:53 AM David Rowley <dgrowleyml@gmail.com> wrote:
> I think the patch is now starting to take shape.  I've added it to the
> September commitfest [1].

This is extremely cool. The memory savings are really nice. And I also
like this:

# Additionally, this commit completely changes the rule that pointers must
# be directly prefixed by the owning memory context and instead, we now
# insist that they're directly prefixed by an 8-byte value where the least
# significant 3-bits are set to a value to indicate which type of memory
# context the pointer belongs to.  Using those 3 bits as an index to a new
# array which stores the methods for each memory context type, we're now
# able to pass the pointer given to functions such as pfree and repalloc to
# the function specific to that context implementation to allow them to
# devise their own methods of finding the memory context which owns the
# given allocated chunk of memory.

That seems like a good system.

This part of the commit message might need to be clarified:

# We also add a restriction that block sizes for all 3 of the memory
# allocators cannot be 1GB or larger.  We would be unable to store the
# number of bytes that the block is offset from the chunk stored beyond this
#1GB boundary on any block that was larger than 1GB.

Earlier in the commit message, you say that allocations of 1GB or more
are stored in dedicated blocks. But here you say that blocks can't be
more than 1GB. Those statements seem to contradict each other. I guess
you mean block sizes for blocks that contain chunks, or something like
that?

-- 
Robert Haas
EDB: http://www.enterprisedb.com





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-09 18:44  Andres Freund <andres@anarazel.de>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 3 replies; 152+ messages in thread

From: Andres Freund @ 2022-08-09 18:44 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: David Rowley <dgrowleyml@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2022-08-09 10:36:57 -0400, Robert Haas wrote:
> On Tue, Aug 9, 2022 at 8:53 AM David Rowley <dgrowleyml@gmail.com> wrote:
> > I think the patch is now starting to take shape.  I've added it to the
> > September commitfest [1].
> 
> This is extremely cool. The memory savings are really nice.

+1


> And I also like this:
> 
> # Additionally, this commit completely changes the rule that pointers must
> # be directly prefixed by the owning memory context and instead, we now
> # insist that they're directly prefixed by an 8-byte value where the least
> # significant 3-bits are set to a value to indicate which type of memory
> # context the pointer belongs to.  Using those 3 bits as an index to a new
> # array which stores the methods for each memory context type, we're now
> # able to pass the pointer given to functions such as pfree and repalloc to
> # the function specific to that context implementation to allow them to
> # devise their own methods of finding the memory context which owns the
> # given allocated chunk of memory.
> 
> That seems like a good system.

I'm obviously biased, but I agree.

I think it's fine, given that we can change this at any time, but it's
probably worth to explicitly agree that this will for now restrict us to 8
context methods?


> This part of the commit message might need to be clarified:
> 
> # We also add a restriction that block sizes for all 3 of the memory
> # allocators cannot be 1GB or larger.  We would be unable to store the
> # number of bytes that the block is offset from the chunk stored beyond this
> #1GB boundary on any block that was larger than 1GB.
> 
> Earlier in the commit message, you say that allocations of 1GB or more
> are stored in dedicated blocks. But here you say that blocks can't be
> more than 1GB. Those statements seem to contradict each other. I guess
> you mean block sizes for blocks that contain chunks, or something like
> that?

I would guess so as well.


> diff --git a/src/include/utils/memutils_internal.h b/src/include/utils/memutils_internal.h
> new file mode 100644
> index 0000000000..2dcfdd7ec3
> --- /dev/null
> +++ b/src/include/utils/memutils_internal.h
> @@ -0,0 +1,117 @@
> +/*-------------------------------------------------------------------------
> + *
> + * memutils_internal.h
> + *	  This file contains declarations for memory allocation utility
> + *	  functions for internal use.
> + *
> + *
> + * Portions Copyright (c) 2022, PostgreSQL Global Development Group
> + * Portions Copyright (c) 1994, Regents of the University of California
> + *
> + * src/include/utils/memutils_internal.h
> + *
> + *-------------------------------------------------------------------------
> + */
> +
> +#ifndef MEMUTILS_INTERNAL_H
> +#define MEMUTILS_INTERNAL_H
> +
> +#include "utils/memutils.h"
> +
> +extern void *AllocSetAlloc(MemoryContext context, Size size);
> +extern void AllocSetFree(void *pointer);
> [much more]

I really wish I knew of a technique to avoid this kind of thing, allowing to
fill a constant array from different translation units... On the linker level
that should be trivial, but I don't think there's a C way to reach that.


> +/*
> + * MemoryContextMethodID
> + *		A unique identifier for each MemoryContext implementation which
> + *		indicates the index into the mcxt_methods[] array. See mcxt.c.
> + */
> +typedef enum MemoryContextMethodID
> +{
> +	MCTX_ASET_ID = 0,

Is there a reason to reserve 0 here? Practically speaking the 8-byte header
will always contain not just zeroes, but I don't think the patch currently
enforces that.  It's probably not worth wasting a "valuable" entry here...


> diff --git a/src/include/utils/memutils_memorychunk.h b/src/include/utils/memutils_memorychunk.h
> new file mode 100644
> index 0000000000..6239cf9008
> --- /dev/null
> +++ b/src/include/utils/memutils_memorychunk.h
> @@ -0,0 +1,185 @@
> +/*-------------------------------------------------------------------------
> + *
> + * memutils_memorychunk.h
> + *	  Here we define a struct named MemoryChunk which implementations of
> + *	  MemoryContexts may use as a header for chunks of memory they allocate.
> + *
> + * A MemoryChunk provides a lightweight header which a MemoryContext can use
> + * to store the size of an allocation and a reference back to the block which
> + * the given chunk is allocated on.
> + *
> + * Although MemoryChunks are used by each of our MemoryContexts, other
> + * implementations may choose to implement their own method for storing chunk
> + * headers.  The only requirement is that the header end with an 8-byte value
> + * which the least significant 3-bits of are set to the MemoryContextMethodID
> + * of the given context.

Well, there can't be other implementations other than ours. So maybe phrase it
as "future implementations"?


> + * By default, a MemoryChunk is 8 bytes in size, however when
> + * MEMORY_CONTEXT_CHECKING is defined the header becomes 16 bytes in size due
> + * to the additional requested_size field.  The MemoryContext may use this
> + * field for whatever they wish, but it is intended to be used for additional
> + * checks which are only done in MEMORY_CONTEXT_CHECKING builds.
> + *
> + * The MemoryChunk contains a uint64 field named 'hdrmask'.  This field is
> + * used to encode 4 separate pieces of information.  Starting with the least
> + * significant bits of 'hdrmask', the bits of this field as used as follows:
> + *
> + * 1.	3-bits to indicate the MemoryContextMethodID
> + * 2.	1-bit to indicate if the chunk is externally managed (see below)
> + * 3.	30-bits for the amount of memory which was reserved for the chunk
> + * 4.	30-bits for the number of bytes that must be subtracted from the chunk
> + *		to obtain the address of the block that the chunk is stored on.
> + *
> + * Because we're limited to a block offset and chunk size of 1GB (30-bits),
> + * any allocation which exceeds this amount must call MemoryChunkSetExternal()
> + * and the MemoryContext must devise its own method for storing the offset for
> + * the block and size of the chunk.

Hm. So really only the first four bits have eactly that layout, correct?
Perhaps that could be clarified somehow?



> + /*
> +  * The maximum size for a memory chunk before it must be externally managed.
> +  */
> +#define MEMORYCHUNK_MAX_SIZE 0x3FFFFFFF
> +
> + /*
> +  * The value to AND onto the hdrmask to determine if it's an externally
> +  * managed memory chunk.
> +  */
> +#define MEMORYCHUNK_EXTERNAL_BIT (1 << 3)

We should probably have a define for the three bits reserved for the context
id, likely in _internal.h


> @@ -109,6 +112,25 @@ typedef struct AllocChunkData *AllocChunk;
>   */
>  typedef void *AllocPointer;
>  
> +/*
> + * AllocFreelistLink
> + *		When pfreeing memory, if we maintain a freelist for the given chunk's
> + *		size then we use a AllocFreelistLink to point to the current item in
> + *		the AllocSetContext's freelist and then set the given freelist element
> + *		to point to the chunk being freed.
> + */
> +typedef struct AllocFreelistLink
> +{
> +	MemoryChunk *next;
> +}			AllocFreelistLink;

I know we have no agreement on that, but I personally would add
AllocFreelistLink to typedefs.list and then re-pgindent ;)


>  /*
>   * AllocSetGetChunkSpace
>   *		Given a currently-allocated chunk, determine the total space
>   *		it occupies (including all memory-allocation overhead).
>   */
> -static Size
> -AllocSetGetChunkSpace(MemoryContext context, void *pointer)
> +Size
> +AllocSetGetChunkSpace(void *pointer)
>  {
> -	AllocChunk	chunk = AllocPointerGetChunk(pointer);
> -	Size		result;
> +	MemoryChunk *chunk = PointerGetMemoryChunk(pointer);
>  
> -	VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN);
> -	result = chunk->size + ALLOC_CHUNKHDRSZ;
> -	VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN);
> -	return result;
> +	if (MemoryChunkIsExternal(chunk))
> +	{

Hm. We don't mark the chunk header as noaccess anymore? If so, why? I realize
it'd be a bit annoying because there's plenty places that look at it, but I
think it's also a good way to catch errors.


> +static const MemoryContextMethods mcxt_methods[] = {
> +	[MCTX_ASET_ID] = {
> +		AllocSetAlloc,
> +		AllocSetFree,
> +		AllocSetRealloc,
> +		AllocSetReset,
> +		AllocSetDelete,
> +		AllocSetGetChunkContext,
> +		AllocSetGetChunkSpace,
> +		AllocSetIsEmpty,
> +		AllocSetStats
> +#ifdef MEMORY_CONTEXT_CHECKING
> +		,AllocSetCheck
> +#endif
> +	},
> +
> +	[MCTX_GENERATION_ID] = {
> +		GenerationAlloc,
> +		GenerationFree,
> +		GenerationRealloc,
> +		GenerationReset,
> +		GenerationDelete,
> +		GenerationGetChunkContext,
> +		GenerationGetChunkSpace,
> +		GenerationIsEmpty,
> +		GenerationStats
> +#ifdef MEMORY_CONTEXT_CHECKING
> +		,GenerationCheck
> +#endif
> +	},
> +
> +	[MCTX_SLAB_ID] = {
> +		SlabAlloc,
> +		SlabFree,
> +		SlabRealloc,
> +		SlabReset,
> +		SlabDelete,
> +		SlabGetChunkContext,
> +		SlabGetChunkSpace,
> +		SlabIsEmpty,
> +		SlabStats
> +#ifdef MEMORY_CONTEXT_CHECKING
> +		,SlabCheck
> +#endif
> +	},
> +};

Mildly wondering whether we ought to use designated initializers instead,
given we're whacking it around already. Too easy to get the order wrong when
adding new members, and we might want to have optional callbacks too.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-09 19:21  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Andres Freund <andres@anarazel.de>
  2 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-08-09 19:21 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Robert Haas <robertmhaas@gmail.com>; David Rowley <dgrowleyml@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Andres Freund <andres@anarazel.de> writes:
> I think it's fine, given that we can change this at any time, but it's
> probably worth to explicitly agree that this will for now restrict us to 8
> context methods?

Do we really need it to be that tight?  I know we only have 3 methods today,
but 8 doesn't seem that far away.  If there were six bits reserved for
this I'd be happier.

>> # We also add a restriction that block sizes for all 3 of the memory
>> # allocators cannot be 1GB or larger.  We would be unable to store the
>> # number of bytes that the block is offset from the chunk stored beyond this
>> #1GB boundary on any block that was larger than 1GB.

Losing MemoryContextAllocHuge would be very bad, so I assume this comment
is not telling the full truth.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-09 19:36  Alvaro Herrera <alvherre@alvh.no-ip.org>
  parent: Andres Freund <andres@anarazel.de>
  2 siblings, 0 replies; 152+ messages in thread

From: Alvaro Herrera @ 2022-08-09 19:36 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Robert Haas <robertmhaas@gmail.com>; David Rowley <dgrowleyml@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On 2022-Aug-09, Andres Freund wrote:

> Mildly wondering whether we ought to use designated initializers instead,
> given we're whacking it around already. Too easy to get the order wrong when
> adding new members, and we might want to have optional callbacks too.

Strong +1.  It makes code much easier to navigate (see XmlTableRoutine
and compare with heapam_methods, for example).

-- 
Álvaro Herrera               48°01'N 7°57'E  —  https://www.EnterpriseDB.com/
Subversion to GIT: the shortest path to happiness I've ever heard of
                                                (Alexey Klyukin)





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-09 21:02  Andres Freund <andres@anarazel.de>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: Andres Freund @ 2022-08-09 21:02 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Robert Haas <robertmhaas@gmail.com>; David Rowley <dgrowleyml@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2022-08-09 15:21:57 -0400, Tom Lane wrote:
> Andres Freund <andres@anarazel.de> writes:
> > I think it's fine, given that we can change this at any time, but it's
> > probably worth to explicitly agree that this will for now restrict us to 8
> > context methods?
> 
> Do we really need it to be that tight?  I know we only have 3 methods today,
> but 8 doesn't seem that far away.  If there were six bits reserved for
> this I'd be happier.

We only have so many bits available, so that'd have to come from some other
resource.  The current division is:

+ * 1.	3-bits to indicate the MemoryContextMethodID
+ * 2.	1-bit to indicate if the chunk is externally managed (see below)
+ * 3.	30-bits for the amount of memory which was reserved for the chunk
+ * 4.	30-bits for the number of bytes that must be subtracted from the chunk
+ *		to obtain the address of the block that the chunk is stored on.

I suspect we could reduce 3) here a bit, which I think would end up with slab
context's max chunkSize shrinking further. Which should still be fine.

But also, we could defer that to later, this is a limit that we can easily
change.


> >> # We also add a restriction that block sizes for all 3 of the memory
> >> # allocators cannot be 1GB or larger.  We would be unable to store the
> >> # number of bytes that the block is offset from the chunk stored beyond this
> >> #1GB boundary on any block that was larger than 1GB.
> 
> Losing MemoryContextAllocHuge would be very bad, so I assume this comment
> is not telling the full truth.

It's just talking about chunked allocation (except for slab, which doesn't
have anything else, but as David pointed out, it makes no sense to use slab
for that large allocations). I.e. it's the max you can pass to
AllocSetContextCreate()'s and GenerationContextCreate()'s maxBlockSize, and to
SlabContextCreate()'s chunkSize.   I don't think we have any code that
currently sets a bigger limit than 8MB.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-09 21:23  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-08-09 21:23 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Robert Haas <robertmhaas@gmail.com>; David Rowley <dgrowleyml@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Andres Freund <andres@anarazel.de> writes:
> On 2022-08-09 15:21:57 -0400, Tom Lane wrote:
>> Do we really need it to be that tight?  I know we only have 3 methods today,
>> but 8 doesn't seem that far away.  If there were six bits reserved for
>> this I'd be happier.

> We only have so many bits available, so that'd have to come from some other
> resource.  The current division is:

> + * 1.	3-bits to indicate the MemoryContextMethodID
> + * 2.	1-bit to indicate if the chunk is externally managed (see below)
> + * 3.	30-bits for the amount of memory which was reserved for the chunk
> + * 4.	30-bits for the number of bytes that must be subtracted from the chunk
> + *		to obtain the address of the block that the chunk is stored on.

> I suspect we could reduce 3) here a bit, which I think would end up with slab
> context's max chunkSize shrinking further. Which should still be fine.

Hmm, I suppose you mean we could reduce 4) if we needed to.  Yeah, that
seems like a reasonable place to buy more bits later if we run out of
MemoryContextMethodIDs.  Should be fine then.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-09 21:28  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-08-09 21:28 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Wed, 10 Aug 2022 at 09:23, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> Andres Freund <andres@anarazel.de> writes:
> > On 2022-08-09 15:21:57 -0400, Tom Lane wrote:
> >> Do we really need it to be that tight?  I know we only have 3 methods today,
> >> but 8 doesn't seem that far away.  If there were six bits reserved for
> >> this I'd be happier.
>
> > We only have so many bits available, so that'd have to come from some other
> > resource.  The current division is:
>
> > + * 1.        3-bits to indicate the MemoryContextMethodID
> > + * 2.        1-bit to indicate if the chunk is externally managed (see below)
> > + * 3.        30-bits for the amount of memory which was reserved for the chunk
> > + * 4.        30-bits for the number of bytes that must be subtracted from the chunk
> > + *           to obtain the address of the block that the chunk is stored on.
>
> > I suspect we could reduce 3) here a bit, which I think would end up with slab
> > context's max chunkSize shrinking further. Which should still be fine.
>
> Hmm, I suppose you mean we could reduce 4) if we needed to.  Yeah, that
> seems like a reasonable place to buy more bits later if we run out of
> MemoryContextMethodIDs.  Should be fine then.

I think he means 3).  If 4) was reduced then that would further reduce
the maxBlockSize we could pass when creating a context.  At least for
aset.c and generation.c, we don't really need 3) to be 30-bits wide as
the set->allocChunkLimit is almost certainly much smaller than that.
Allocations bigger than allocChunkLimit use a dedicated block with an
external chunk. External chunks don't use 3) or 4).

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-09 21:44  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 0 replies; 152+ messages in thread

From: Tom Lane @ 2022-08-09 21:44 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> On Wed, 10 Aug 2022 at 09:23, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> Hmm, I suppose you mean we could reduce 4) if we needed to.  Yeah, that
>> seems like a reasonable place to buy more bits later if we run out of
>> MemoryContextMethodIDs.  Should be fine then.

> I think he means 3).  If 4) was reduced then that would further reduce
> the maxBlockSize we could pass when creating a context.  At least for
> aset.c and generation.c, we don't really need 3) to be 30-bits wide as
> the set->allocChunkLimit is almost certainly much smaller than that.

Oh, I see: we'd just be further constraining the size of chunk that
has to be pushed out as an "external" chunk.  Got it.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-09 23:17  David Rowley <dgrowleyml@gmail.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 0 replies; 152+ messages in thread

From: David Rowley @ 2022-08-09 23:17 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Thanks for giving this a look.

On Wed, 10 Aug 2022 at 02:37, Robert Haas <robertmhaas@gmail.com> wrote:
> # We also add a restriction that block sizes for all 3 of the memory
> # allocators cannot be 1GB or larger.  We would be unable to store the
> # number of bytes that the block is offset from the chunk stored beyond this
> #1GB boundary on any block that was larger than 1GB.
>
> Earlier in the commit message, you say that allocations of 1GB or more
> are stored in dedicated blocks. But here you say that blocks can't be
> more than 1GB. Those statements seem to contradict each other. I guess
> you mean block sizes for blocks that contain chunks, or something like
> that?

I'll update that so it's more clear.

But, just to clarify here first, the 1GB restriction is just in
regards to the maxBlockSize parameter when creating a context.
Anything over set->allocChunkLimit goes on a dedicated block and there
is no 1GB size restriction on those dedicated blocks.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-10 06:33  David Rowley <dgrowleyml@gmail.com>
  parent: Andres Freund <andres@anarazel.de>
  2 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-08-10 06:33 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

 On Wed, 10 Aug 2022 at 06:44, Andres Freund <andres@anarazel.de> wrote:
> I think it's fine, given that we can change this at any time, but it's
> probably worth to explicitly agree that this will for now restrict us to 8
> context methods?

I know there was some discussion about this elsewhere in this thread
about 8 possibly not being enough, but that seems to have concluded
with we'll just make more space if we ever need to.

To make that easier, I've adapted the code in memutils_memorychunk.h
to separate out the max values for the block offset from the max value
for the chunk size. The chunk size is the one we'd likely want to
lower if we ever needed more bits.  I think this also helps document
the maxBlockSize limitations in aset.c and generation.c.

> > +/*
> > + * MemoryContextMethodID
> > + *           A unique identifier for each MemoryContext implementation which
> > + *           indicates the index into the mcxt_methods[] array. See mcxt.c.
> > + */
> > +typedef enum MemoryContextMethodID
> > +{
> > +     MCTX_ASET_ID = 0,
>
> Is there a reason to reserve 0 here? Practically speaking the 8-byte header
> will always contain not just zeroes, but I don't think the patch currently
> enforces that.  It's probably not worth wasting a "valuable" entry here...

The code was just being explicit about that being set to 0. I'm not
really sure I see this as reserving 0.  I've removed the = 0 anyway
since it wasn't really doing anything useful.

> > + * Although MemoryChunks are used by each of our MemoryContexts, other
> > + * implementations may choose to implement their own method for storing chunk

> Well, there can't be other implementations other than ours. So maybe phrase it
> as "future implementations"?

Yeah, that seems better.

> > + * 1.        3-bits to indicate the MemoryContextMethodID
> > + * 2.        1-bit to indicate if the chunk is externally managed (see below)
> > + * 3.        30-bits for the amount of memory which was reserved for the chunk
> > + * 4.        30-bits for the number of bytes that must be subtracted from the chunk
> > + *           to obtain the address of the block that the chunk is stored on.

> Hm. So really only the first four bits have eactly that layout, correct?
> Perhaps that could be clarified somehow?

I've clarified that #3 and #4 are unused in external chunks.

> > +#define MEMORYCHUNK_EXTERNAL_BIT (1 << 3)
>
> We should probably have a define for the three bits reserved for the context
> id, likely in _internal.h

I've added both MEMORY_CONTEXT_METHODID_BITS and
MEMORY_CONTEXT_METHODID_MASK and tidied up the defines in
memutils_memorychunk.h so that they'll follow on from whatever
MEMORY_CONTEXT_METHODID_BITS is set to.

> > +typedef struct AllocFreelistLink
> > +{
> > +     MemoryChunk *next;
> > +}                    AllocFreelistLink;
>
> I know we have no agreement on that, but I personally would add
> AllocFreelistLink to typedefs.list and then re-pgindent ;)

I tend to leave that up to the build farm to generate. I really wasn't
sure which should sort first out of the following:

MemoryContextMethods
MemoryContextMethodID

The correct answer depends on if the sort is case-sensitive or not. I
imagine it is since it is in C, but don't really know if the buildfarm
will generate the same.

I've added them in the above order now.

> Hm. We don't mark the chunk header as noaccess anymore? If so, why? I realize
> it'd be a bit annoying because there's plenty places that look at it, but I
> think it's also a good way to catch errors.

I don't think I've really changed anything here.  If I understand
correctly the pointer to the MemoryContext was not marked as NOACCESS
before. I guessed that's because it's accessed outside of aset.c. I've
kept that due to how the 3 lower bits are still accessed outside of
aset.c. It's just that we're stuffing more information into that
8-byte variable now.

> > +static const MemoryContextMethods mcxt_methods[] = {
...
> Mildly wondering whether we ought to use designated initializers instead,
> given we're whacking it around already. Too easy to get the order wrong when
> adding new members, and we might want to have optional callbacks too.

I've adjusted how this array is initialized now.

I've attached version 3 of the patch.

Thanks for having a look at this.

David

Attachments:

v3-0001-Improve-performance-of-and-reduce-overheads-of-me.patch (text/plain, 99.3K) download From 869e238f6fcfc54e7e2da2c35e3dde99f61488a6 Mon Sep 17 00:00:00 2001 From: David Rowley <dgrowley@gmail.com> Date: Thu, 9 Jun 2022 20:09:22 +1200 Subject: [PATCH v3] Improve performance of and reduce overheads of memory management Whenever we palloc a chunk of memory, traditionally, we prefix the returned pointer with a pointer to the memory context to which the chunk belongs. This is required so that we're able to easily determine the owning context when performing operations such as pfree() and repalloc(). For the AllocSet context, prior to this commit we additionally prefixed the pointer to the owning context with the size of the chunk. This made the header 16 bytes in size. This 16-byte overhead was required for all AllocSet allocations regardless of the allocation size. For the generation context, the problem was worse; in addition to the pointer to the owning context and chunk size, we also stored a pointer to the owning block so that we could track the number of freed chunks on a block. The slab allocator had a 16-byte chunk header. The changes being made here reduce the chunk header size down to just 8 bytes for all 3 of our memory context types. For small to medium sized allocations, this significantly increases the number of chunks that we can fit on a given block which results in much more efficient use of memory. Additionally, this commit completely changes the rule that pointers to palloc'd memory must be directly prefixed by a pointer to the owning memory context and instead, we now insist that they're directly prefixed by an 8-byte value where the least significant 3-bits are set to a value to indicate which type of memory context the pointer belongs to. Using those 3 bits as an index (known as MemoryContextMethodID) to a new array which stores the methods for each memory context type, we're now able to pass the pointer given to functions such as pfree() and repalloc() to the function specific to that context implementation to allow them to devise their own methods of finding the memory context which owns the given allocated chunk of memory. Using 3-bits for the MemoryContextMethodID does mean we're limiting ourselves to only having a maximum of 8 different memory context types. We could reduce the bit space for the chunk size a little to make way for more than 3 bits, but it seems like it might be better to do that only if we ever need more than 8 context types. This would only be a problem if some future memory context type which does not use MemoryChunk really couldn't give up any of the 61 remaining bits in the chunk header. The reason we're able to reduce the chunk header down to just 8 bytes is because of the way we make use of the remaining 61 bits of the required 8-byte chunk header. Here we also implement a general-purpose MemoryChunk struct which makes use of those 61 remaining bits to store the size of the chunk and the number of bytes which must be subtracted from the chunk to get a reference to the block that the chunk is stored on. We reserve 30 bits each for these fields and the 1 additional remaining bit to denote if the chunk is an "external" chunk or not. External here means that the chunk header does not store the chunk size or block offset. The MemoryContext can use these external chunks at any time, but must use them if either the chunk size or block offset cannot be represented by the 30 bits (1GB) that are reserved for each of these values. It is up to the MemoryContext to devise its own means to determine the chunk size and block offset for external chunks. With this MemoryChunk, each of our 3 memory context types can quickly obtain a reference to the block any given chunk is located on. AllocSet is able to find the context to which the chunk is owned by first obtaining a reference to the block by subtracting the block offset as is stored in the 'hdrmask' field and then referencing the block's 'aset' field. The Generation context uses the same method, but GenerationBlock did not have a field pointing back to the owning context, so one is added by this commit. In aset.c and generation.c, all allocations larger than allocChunkLimit are stored on dedicated blocks. When there's just a single chunk on a block like this, it's easy to find the block from the chunk, we just subtract the size of the block header from the chunk pointer. The size of these chunks is also known as we store the endptr on the block, so we can just subtract the pointer to the allocated memory from that. Because we can easily find the owning block and the size of the chunk for these dedicated blocks, we just always use external chunks for allocation sizes larger than allocChunkLimit. This sidesteps the problem of non-external MemoryChunks being unable to represent chunk sizes >= 1GB. For the slab allocator, this commit adds a new restriction that slab chunks cannot be >= 1GB in size. If there happened to be any users of slab.c which used chunk sizes this large, they really should be using AllocSet instead. Here we also add a restriction that normal non-dedicated blocks cannot be 1GB or larger. It's now not possible to pass a 'maxBlockSize' >= 1GB during the creation of an AllocSet or Generation context. Allocations can still be larger than 1GB, it's just these will always be on dedicated blocks (which are not restricted to 1GB in size). Author: Andres Freund, David Rowley Discussion: https://postgr.es/m/CAApHDvpjauCRXcgcaL6+e3eqecEHoeRm9D-kcbuvBitgPnW=vw@mail.gmail.com --- src/backend/utils/mmgr/README | 60 ++- src/backend/utils/mmgr/aset.c | 459 ++++++++++++----------- src/backend/utils/mmgr/generation.c | 331 ++++++++-------- src/backend/utils/mmgr/mcxt.c | 84 ++++- src/backend/utils/mmgr/slab.c | 197 ++++------ src/include/nodes/memnodes.h | 7 +- src/include/utils/memutils.h | 48 +-- src/include/utils/memutils_internal.h | 130 +++++++ src/include/utils/memutils_memorychunk.h | 210 +++++++++++ src/tools/pgindent/typedefs.list | 3 + 10 files changed, 961 insertions(+), 568 deletions(-) create mode 100644 src/include/utils/memutils_internal.h create mode 100644 src/include/utils/memutils_memorychunk.h diff --git a/src/backend/utils/mmgr/README b/src/backend/utils/mmgr/README index 221b4bd343..2c98e92b69 100644 --- a/src/backend/utils/mmgr/README +++ b/src/backend/utils/mmgr/README @@ -378,35 +378,55 @@ MemoryContext like the parent and child contexts, and the name of the context. This is essentially an abstract superclass, and the behavior is -determined by the "methods" pointer is its virtual function table -(struct MemoryContextMethods). Specific memory context types will use -derived structs having these fields as their first fields. All the +determined by the "methods" pointer which references which set of +MemoryContextMethods are to be used. Specific memory context types will +use derived structs having these fields as their first fields. All the contexts of a specific type will have methods pointers that point to -the same static table of function pointers. +the corresponding element in the mcxt_methods[] array as defined in mcxt.c. While operations like allocating from and resetting a context take the relevant MemoryContext as a parameter, operations like free and realloc are trickier. To make those work, we require all memory context types to produce allocated chunks that are immediately, -without any padding, preceded by a pointer to the corresponding -MemoryContext. +without any padding, preceded by a uint64 value of which the least +significant 3 bits are set to the owning context's MemoryContextMethodID. +This allows the code to determine the correct MemoryContextMethods to +use by looking up the mcxt_methods[] array using the 3 bits as an index +into that array. If a type of allocator needs additional information about its chunks, like e.g. the size of the allocation, that information can in turn -precede the MemoryContext. This means the only overhead implied by -the memory context mechanism is a pointer to its context, so we're not -constraining context-type designers very much. - -Given this, routines like pfree determine their corresponding context -with an operation like (although that is usually encapsulated in -GetMemoryChunkContext()) - - MemoryContext context = *(MemoryContext*) (((char *) pointer) - sizeof(void *)); - -and then invoke the corresponding method for the context - - context->methods->free_p(pointer); - +either be encoded into the remaining 61 bits of the preceding uint64 value +or if more space is required, additional values may be stored directly prior +to the uint64 value. It is up to the context implementation to manage this. + +Given this, routines like pfree can determine which set of +MemoryContextMethods to call the free_p function for by calling +GetMemoryChunkMethodID() and finding the corresponding MemoryContextMethods +in the mcxt_methods array[]. For convenience, the MCXT_METHOD() macro is +provided, making the code as simple as: + +void +pfree(void *pointer) +{ + MCXT_METHOD(pointer, free_p)(pointer); +} + +All of the current memory contexts make use of the MemoryChunk header type +which is defined in memutils_memorychunk.h. This suits all of the existing +context types well as it makes use of the remaining 61-bits of the uint64 +header to efficiently encode the size of the chunk of memory and the number of +bytes which must be subtracted from the chunk in order to obtain a reference +to the block that the chunk belongs to. 30 bits are used for each of these. +If more than 30 bits are required (i.e. > 1GB) then the memory context must +manage that itself. This can be done by calling the +MemoryChunkSetHdrMaskExternal() function on the given chunk. Currently, each +memory context type stores large allocations on dedicated blocks (which always +contain only a single chunk). For these, finding the block is simple as we +know that the chunk must be the first on the given block, so the block is +always at a fixed offset to the chunk. For these, finding the size of the +chunk is also simple as the block always stores an endptr which we can use to +calculate the size of the chunk. More Control Over aset.c Behavior --------------------------------- diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index ec3e264a73..447ab5ab67 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -49,6 +49,8 @@ #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" /*-------------------- * Chunk freelist k holds chunks of size 1 << (k + ALLOC_MINBITS), @@ -66,7 +68,9 @@ * CAUTION: ALLOC_MINBITS must be large enough so that * 1<<ALLOC_MINBITS is at least MAXALIGN, * or we may fail to align the smallest chunks adequately. - * 8-byte alignment is enough on all currently known machines. + * 8-byte alignment is enough on all currently known machines. This 8-byte + * minimum also allows us to store a pointer to the next freelist item within + * the chunk of memory itself. * * With the current parameters, request sizes up to 8K are treated as chunks, * larger requests go into dedicated blocks. Change ALLOCSET_NUM_FREELISTS @@ -98,10 +102,9 @@ */ #define ALLOC_BLOCKHDRSZ MAXALIGN(sizeof(AllocBlockData)) -#define ALLOC_CHUNKHDRSZ sizeof(struct AllocChunkData) +#define ALLOC_CHUNKHDRSZ sizeof(MemoryChunk) typedef struct AllocBlockData *AllocBlock; /* forward reference */ -typedef struct AllocChunkData *AllocChunk; /* * AllocPointer @@ -109,6 +112,25 @@ typedef struct AllocChunkData *AllocChunk; */ typedef void *AllocPointer; +/* + * AllocFreelistLink + * When pfreeing memory, if we maintain a freelist for the given chunk's + * size then we use a AllocFreelistLink to point to the current item in + * the AllocSetContext's freelist and then set the given freelist element + * to point to the chunk being freed. + */ +typedef struct AllocFreelistLink +{ + MemoryChunk *next; +} AllocFreelistLink; + +/* + * Obtain a AllocFreelistLink for the given chunk. Allocation sizes are + * always at least sizeof(AllocFreelistLink), so we reuse the pointer's memory + * itself to store the freelist link + */ +#define GetFreeListLink(c, sz) ((AllocFreelistLink *) ((char *) (c) + ALLOC_CHUNKHDRSZ)) + /* * AllocSetContext is our standard implementation of MemoryContext. * @@ -123,7 +145,7 @@ typedef struct AllocSetContext MemoryContextData header; /* Standard memory-context fields */ /* Info about storage allocated in this context: */ AllocBlock blocks; /* head of list of blocks in this set */ - AllocChunk freelist[ALLOCSET_NUM_FREELISTS]; /* free chunk lists */ + MemoryChunk *freelist[ALLOCSET_NUM_FREELISTS]; /* free chunk lists */ /* Allocation parameters for this context: */ Size initBlockSize; /* initial block size */ Size maxBlockSize; /* maximum block size */ @@ -139,8 +161,8 @@ typedef AllocSetContext *AllocSet; /* * AllocBlock * An AllocBlock is the unit of memory that is obtained by aset.c - * from malloc(). It contains one or more AllocChunks, which are - * the units requested by palloc() and freed by pfree(). AllocChunks + * from malloc(). It contains one or more MemoryChunks, which are + * the units requested by palloc() and freed by pfree(). MemoryChunks * cannot be returned to malloc() individually, instead they are put * on freelists by pfree() and re-used by the next palloc() that has * a matching request size. @@ -158,48 +180,12 @@ typedef struct AllocBlockData } AllocBlockData; /* - * AllocChunk - * The prefix of each piece of memory in an AllocBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "aset" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). We simplify matters for this - * module by requiring sizeof(AllocChunkData) to be maxaligned, and then - * we can ensure things work by adding any required alignment padding before - * the "aset" field. There is a static assertion below that the alignment - * is done correctly. - */ -typedef struct AllocChunkData -{ - /* size is always the size of the usable space in the chunk */ - Size size; -#ifdef MEMORY_CONTEXT_CHECKING - /* when debugging memory usage, also store actual requested size */ - /* this is zero in a free chunk */ - Size requested_size; - -#define ALLOCCHUNK_RAWSIZE (SIZEOF_SIZE_T * 2 + SIZEOF_VOID_P) -#else -#define ALLOCCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P) -#endif /* MEMORY_CONTEXT_CHECKING */ - - /* ensure proper alignment by adding padding if needed */ -#if (ALLOCCHUNK_RAWSIZE % MAXIMUM_ALIGNOF) != 0 - char padding[MAXIMUM_ALIGNOF - ALLOCCHUNK_RAWSIZE % MAXIMUM_ALIGNOF]; -#endif - - /* aset is the owning aset if allocated, or the freelist link if free */ - void *aset; - /* there must not be any padding to reach a MAXALIGN boundary here! */ -} AllocChunkData; - -/* - * Only the "aset" field should be accessed outside this module. + * Only the "hdrmask" field should be accessed outside this module. * We keep the rest of an allocated chunk's header marked NOACCESS when using * valgrind. But note that chunk headers that are in a freelist are kept * accessible, for simplicity. */ -#define ALLOCCHUNK_PRIVATE_LEN offsetof(AllocChunkData, aset) +#define ALLOCCHUNK_PRIVATE_LEN offsetof(MemoryChunk, hdrmask) /* * AllocPointerIsValid @@ -213,10 +199,12 @@ typedef struct AllocChunkData */ #define AllocSetIsValid(set) PointerIsValid(set) -#define AllocPointerGetChunk(ptr) \ - ((AllocChunk)(((char *)(ptr)) - ALLOC_CHUNKHDRSZ)) -#define AllocChunkGetPointer(chk) \ - ((AllocPointer)(((char *)(chk)) + ALLOC_CHUNKHDRSZ)) +/* + * We always store external chunks on a dedicated block. This makes fetching + * the block from an external chunk easy since it's always the first and only + * chunk on the block. + */ +#define ExternalChunkGetBlock(chunk) (AllocBlock) ((char *) chunk - ALLOC_BLOCKHDRSZ) /* * Rather than repeatedly creating and deleting memory contexts, we keep some @@ -260,42 +248,6 @@ static AllocSetFreeList context_freelists[2] = } }; -/* - * These functions implement the MemoryContext API for AllocSet contexts. - */ -static void *AllocSetAlloc(MemoryContext context, Size size); -static void AllocSetFree(MemoryContext context, void *pointer); -static void *AllocSetRealloc(MemoryContext context, void *pointer, Size size); -static void AllocSetReset(MemoryContext context); -static void AllocSetDelete(MemoryContext context); -static Size AllocSetGetChunkSpace(MemoryContext context, void *pointer); -static bool AllocSetIsEmpty(MemoryContext context); -static void AllocSetStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); - -#ifdef MEMORY_CONTEXT_CHECKING -static void AllocSetCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for AllocSet contexts. - */ -static const MemoryContextMethods AllocSetMethods = { - AllocSetAlloc, - AllocSetFree, - AllocSetRealloc, - AllocSetReset, - AllocSetDelete, - AllocSetGetChunkSpace, - AllocSetIsEmpty, - AllocSetStats -#ifdef MEMORY_CONTEXT_CHECKING - ,AllocSetCheck -#endif -}; - /* ---------- * AllocSetFreeIndex - @@ -387,18 +339,21 @@ AllocSetContextCreateInternal(MemoryContext parent, AllocSet set; AllocBlock block; - /* Assert we padded AllocChunkData properly */ + /* ensure MemoryChunk's size is properly maxaligned */ StaticAssertStmt(ALLOC_CHUNKHDRSZ == MAXALIGN(ALLOC_CHUNKHDRSZ), - "sizeof(AllocChunkData) is not maxaligned"); - StaticAssertStmt(offsetof(AllocChunkData, aset) + sizeof(MemoryContext) == - ALLOC_CHUNKHDRSZ, - "padding calculation in AllocChunkData is wrong"); + "sizeof(MemoryChunk) is not maxaligned"); /* * First, validate allocation parameters. Once these were regular runtime * test and elog's, but in practice Asserts seem sufficient because nobody * varies their parameters at runtime. We somewhat arbitrarily enforce a - * minimum 1K block size. + * minimum 1K block size. We restrict the maximum block size to + * MEMORYCHUNK_MAX_BLOCKOFFSET as MemoryChunks are limited to this in + * regards to addressing the offset between the chunk and the block that + * the chunk is stored on. We would be unable to store the offset between + * the chunk and block for any chunks that were beyond + * MEMORYCHUNK_MAX_BLOCKOFFSET bytes into the block if the block was to be + * larger than this. */ Assert(initBlockSize == MAXALIGN(initBlockSize) && initBlockSize >= 1024); @@ -409,6 +364,7 @@ AllocSetContextCreateInternal(MemoryContext parent, (minContextSize == MAXALIGN(minContextSize) && minContextSize >= 1024 && minContextSize <= maxBlockSize)); + Assert(maxBlockSize <= MEMORYCHUNK_MAX_BLOCKOFFSET); /* * Check whether the parameters match either available freelist. We do @@ -443,7 +399,7 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Reinitialize its header, installing correct name and parent */ MemoryContextCreate((MemoryContext) set, T_AllocSetContext, - &AllocSetMethods, + MCTX_ASET_ID, parent, name); @@ -519,14 +475,18 @@ AllocSetContextCreateInternal(MemoryContext parent, * * We have to have allocChunkLimit a power of two, because the requested * and actually-allocated sizes of any chunk must be on the same side of - * the limit, else we get confused about whether the chunk is "big". + * the limit, else we get confused about whether the chunk is on a + * dedicated block. * - * Also, allocChunkLimit must not exceed ALLOCSET_SEPARATE_THRESHOLD. + * Also, allocChunkLimit must not exceed ALLOCSET_SEPARATE_THRESHOLD. We + * must also ensure allocChunkLimit is <= to MEMORYCHUNK_MAX_CHUNKSIZE as + * anything larger than MEMORYCHUNK_MAX_CHUNKSIZE requires an "external" + * MemoryChunk, and we only do those for allocations > allocChunkLimit. */ StaticAssertStmt(ALLOC_CHUNK_LIMIT == ALLOCSET_SEPARATE_THRESHOLD, "ALLOC_CHUNK_LIMIT != ALLOCSET_SEPARATE_THRESHOLD"); - set->allocChunkLimit = ALLOC_CHUNK_LIMIT; + set->allocChunkLimit = Min(ALLOC_CHUNK_LIMIT, MEMORYCHUNK_MAX_CHUNKSIZE); while ((Size) (set->allocChunkLimit + ALLOC_CHUNKHDRSZ) > (Size) ((maxBlockSize - ALLOC_BLOCKHDRSZ) / ALLOC_CHUNK_FRACTION)) set->allocChunkLimit >>= 1; @@ -534,7 +494,7 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) set, T_AllocSetContext, - &AllocSetMethods, + MCTX_ASET_ID, parent, name); @@ -555,7 +515,7 @@ AllocSetContextCreateInternal(MemoryContext parent, * thrash malloc() when a context is repeatedly reset after small allocations, * which is typical behavior for per-tuple contexts. */ -static void +void AllocSetReset(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -623,7 +583,7 @@ AllocSetReset(MemoryContext context) * * Unlike AllocSetReset, this *must* free all resources of the set. */ -static void +void AllocSetDelete(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -717,12 +677,12 @@ AllocSetDelete(MemoryContext context) * is marked, as mcxt.c will set it to UNDEFINED. In some paths we will * return space that is marked NOACCESS - AllocSetRealloc has to beware! */ -static void * +void * AllocSetAlloc(MemoryContext context, Size size) { AllocSet set = (AllocSet) context; AllocBlock block; - AllocChunk chunk; + MemoryChunk *chunk; int fidx; Size chunk_size; Size blksize; @@ -746,18 +706,20 @@ AllocSetAlloc(MemoryContext context, Size size) block->aset = set; block->freeptr = block->endptr = ((char *) block) + blksize; - chunk = (AllocChunk) (((char *) block) + ALLOC_BLOCKHDRSZ); - chunk->aset = set; - chunk->size = chunk_size; + chunk = (MemoryChunk *) (((char *) block) + ALLOC_BLOCKHDRSZ); + + /* mark the MemoryChunk as externally managed */ + MemoryChunkSetHdrMaskExternal(chunk, MCTX_ASET_ID); + #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk_size) - set_sentinel(AllocChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* @@ -780,13 +742,13 @@ AllocSetAlloc(MemoryContext context, Size size) } /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -799,31 +761,37 @@ AllocSetAlloc(MemoryContext context, Size size) chunk = set->freelist[fidx]; if (chunk != NULL) { - Assert(chunk->size >= size); + AllocFreelistLink *link; - set->freelist[fidx] = (AllocChunk) chunk->aset; + Assert(MemoryChunkGetSize(chunk) >= size); - chunk->aset = (void *) set; + chunk_size = (1 << ALLOC_MINBITS) << fidx; + link = GetFreeListLink(chunk, chunk_size); + + /* pop this chunk off the freelist */ + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + set->freelist[fidx] = link->next; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(AllocChunkGetPointer(chunk), size); + if (size < MemoryChunkGetSize(chunk)) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, - chunk->size - size); + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, + MemoryChunkGetSize(chunk) - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -856,6 +824,7 @@ AllocSetAlloc(MemoryContext context, Size size) */ while (availspace >= ((1 << ALLOC_MINBITS) + ALLOC_CHUNKHDRSZ)) { + AllocFreelistLink *link; Size availchunk = availspace - ALLOC_CHUNKHDRSZ; int a_fidx = AllocSetFreeIndex(availchunk); @@ -871,22 +840,26 @@ AllocSetAlloc(MemoryContext context, Size size) availchunk = ((Size) 1 << (a_fidx + ALLOC_MINBITS)); } - chunk = (AllocChunk) (block->freeptr); + chunk = (MemoryChunk *) (block->freeptr); /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, ALLOC_CHUNKHDRSZ); - block->freeptr += (availchunk + ALLOC_CHUNKHDRSZ); availspace -= (availchunk + ALLOC_CHUNKHDRSZ); - chunk->size = availchunk; + MemoryChunkSetHdrMask(chunk, block, availchunk, MCTX_ASET_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = 0; /* mark it free */ #endif - chunk->aset = (void *) set->freelist[a_fidx]; + /* push this chunk onto the freelist */ + link = GetFreeListLink(chunk, availspace); + + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + link->next = set->freelist[a_fidx]; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); + set->freelist[a_fidx] = chunk; } - /* Mark that we need to create a new block */ block = NULL; } @@ -954,7 +927,7 @@ AllocSetAlloc(MemoryContext context, Size size) /* * OK, do the allocation */ - chunk = (AllocChunk) (block->freeptr); + chunk = (MemoryChunk *) (block->freeptr); /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, ALLOC_CHUNKHDRSZ); @@ -962,67 +935,66 @@ AllocSetAlloc(MemoryContext context, Size size) block->freeptr += (chunk_size + ALLOC_CHUNKHDRSZ); Assert(block->freeptr <= block->endptr); - chunk->aset = (void *) set; - chunk->size = chunk_size; + MemoryChunkSetHdrMask(chunk, block, chunk_size, MCTX_ASET_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(AllocChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * AllocSetFree * Frees allocated memory; memory is removed from the set. */ -static void -AllocSetFree(MemoryContext context, void *pointer) +void +AllocSetFree(void *pointer) { - AllocSet set = (AllocSet) context; - AllocChunk chunk = AllocPointerGetChunk(pointer); + AllocSet set; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); + if (MemoryChunkIsExternal(chunk)) + { + + AllocBlock block = ExternalChunkGetBlock(chunk); + + set = block->aset; + #ifdef MEMORY_CONTEXT_CHECKING - /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunk->size) - if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", - set->header.name, chunk); + { + Size chunk_size = block->endptr - (char *) pointer; + + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < chunk_size) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); + } #endif - if (chunk->size > set->allocChunkLimit) - { - /* - * Big chunks are certain to have been allocated as single-chunk - * blocks. Just unlink that block and return it to malloc(). - */ - AllocBlock block = (AllocBlock) (((char *) chunk) - ALLOC_BLOCKHDRSZ); /* - * Try to verify that we have a sane block pointer: it should - * reference the correct aset, and freeptr and endptr should point - * just past the chunk. + * Try to verify that we have a sane block pointer, the freeptr should + * match the endptr. */ - if (block->aset != set || - block->freeptr != block->endptr || - block->freeptr != ((char *) block) + - (chunk->size + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) + if (block->freeptr != block->endptr) elog(ERROR, "could not find block containing chunk %p", chunk); /* OK, remove block from aset's list and free it */ @@ -1033,7 +1005,7 @@ AllocSetFree(MemoryContext context, void *pointer) if (block->next) block->next->prev = block->prev; - context->mem_allocated -= block->endptr - ((char *) block); + set->header.mem_allocated -= block->endptr - ((char *) block); #ifdef CLOBBER_FREED_MEMORY wipe_mem(block, block->freeptr - ((char *) block)); @@ -1042,20 +1014,37 @@ AllocSetFree(MemoryContext context, void *pointer) } else { - /* Normal case, put the chunk into appropriate freelist */ - int fidx = AllocSetFreeIndex(chunk->size); + AllocBlock block = MemoryChunkGetBlock(chunk); + Size chunk_size = MemoryChunkGetSize(chunk); + AllocFreelistLink *link = GetFreeListLink(chunk, chunksize); + int fidx; - chunk->aset = (void *) set->freelist[fidx]; + set = block->aset; + +#ifdef MEMORY_CONTEXT_CHECKING + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < chunk_size) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); +#endif #ifdef CLOBBER_FREED_MEMORY - wipe_mem(pointer, chunk->size); + wipe_mem(pointer, chunk_size); #endif + /* Normal case, put the chunk into appropriate freelist */ + fidx = AllocSetFreeIndex(chunk_size); + + /* push this chunk onto the top of the freelist for this chunk size */ + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + link->next = set->freelist[fidx]; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); + set->freelist[fidx] = chunk; #ifdef MEMORY_CONTEXT_CHECKING /* Reset requested_size to 0 in chunks that are on freelist */ chunk->requested_size = 0; #endif - set->freelist[fidx] = chunk; } } @@ -1071,17 +1060,28 @@ AllocSetFree(MemoryContext context, void *pointer) * (In principle, we could use VALGRIND_GET_VBITS() to rediscover the old * request size.) */ -static void * -AllocSetRealloc(MemoryContext context, void *pointer, Size size) +void * +AllocSetRealloc(void *pointer, Size size) { - AllocSet set = (AllocSet) context; - AllocChunk chunk = AllocPointerGetChunk(pointer); + AllocBlock block; + AllocSet set; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); Size oldsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - oldsize = chunk->size; + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); + oldsize = block->endptr - (char *) pointer; + } + else + { + block = MemoryChunkGetBlock(chunk); + oldsize = MemoryChunkGetSize(chunk); + } + set = block->aset; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ @@ -1091,37 +1091,25 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) set->header.name, chunk); #endif - if (oldsize > set->allocChunkLimit) + if (MemoryChunkIsExternal(chunk)) { /* * The chunk must have been allocated as a single-chunk block. Use * realloc() to make the containing block bigger, or smaller, with * minimum space wastage. */ - AllocBlock block = (AllocBlock) (((char *) chunk) - ALLOC_BLOCKHDRSZ); Size chksize; Size blksize; Size oldblksize; /* - * Try to verify that we have a sane block pointer: it should - * reference the correct aset, and freeptr and endptr should point - * just past the chunk. + * Try to verify that we have a sane block pointer, the freeptr should + * match the endptr. */ - if (block->aset != set || - block->freeptr != block->endptr || - block->freeptr != ((char *) block) + - (oldsize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) + if (block->freeptr != block->endptr) elog(ERROR, "could not find block containing chunk %p", chunk); - /* - * Even if the new request is less than set->allocChunkLimit, we stick - * with the single-chunk block approach. Therefore we need - * chunk->size to be bigger than set->allocChunkLimit, so we don't get - * confused about the chunk's status in future calls. - */ - chksize = Max(size, set->allocChunkLimit + 1); - chksize = MAXALIGN(chksize); + chksize = MAXALIGN(size); /* Do the realloc */ blksize = chksize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ; @@ -1136,21 +1124,20 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) } /* updated separately, not to underflow when (oldblksize > blksize) */ - context->mem_allocated -= oldblksize; - context->mem_allocated += blksize; + set->header.mem_allocated -= oldblksize; + set->header.mem_allocated += blksize; block->freeptr = block->endptr = ((char *) block) + blksize; /* Update pointers since block has likely been moved */ - chunk = (AllocChunk) (((char *) block) + ALLOC_BLOCKHDRSZ); - pointer = AllocChunkGetPointer(chunk); + chunk = (MemoryChunk *) (((char *) block) + ALLOC_BLOCKHDRSZ); + pointer = MemoryChunkGetPointer(chunk); if (block->prev) block->prev->next = block; else set->blocks = block; if (block->next) block->next->prev = block; - chunk->size = chksize; #ifdef MEMORY_CONTEXT_CHECKING #ifdef RANDOMIZE_ALLOCATED_MEMORY @@ -1172,9 +1159,8 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) #endif chunk->requested_size = size; - /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) + if (size < chksize) set_sentinel(pointer, size); #else /* !MEMORY_CONTEXT_CHECKING */ @@ -1289,34 +1275,58 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) memcpy(newPointer, pointer, oldsize); /* free old chunk */ - AllocSetFree((MemoryContext) set, pointer); + AllocSetFree(pointer); return newPointer; } } +/* + * AllocSetGetChunkContext + * Return the MemoryContext that 'pointer' belongs to. + */ +MemoryContext +AllocSetGetChunkContext(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + AllocBlock block; + AllocSet set; + + if (MemoryChunkIsExternal(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (AllocBlock) MemoryChunkGetBlock(chunk); + + set = block->aset; + + return &set->header; +} + /* * AllocSetGetChunkSpace * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -AllocSetGetChunkSpace(MemoryContext context, void *pointer) +Size +AllocSetGetChunkSpace(void *pointer) { - AllocChunk chunk = AllocPointerGetChunk(pointer); - Size result; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); - VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - result = chunk->size + ALLOC_CHUNKHDRSZ; - VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return result; + if (MemoryChunkIsExternal(chunk)) + { + AllocBlock block = ExternalChunkGetBlock(chunk); + + return block->endptr - (char *) chunk; + } + + return MemoryChunkGetSize(chunk) + ALLOC_CHUNKHDRSZ; } /* * AllocSetIsEmpty * Is an allocset empty of any allocated space? */ -static bool +bool AllocSetIsEmpty(MemoryContext context) { /* @@ -1339,7 +1349,7 @@ AllocSetIsEmpty(MemoryContext context) * totals: if not NULL, add stats about this context into *totals. * print_to_stderr: print stats to stderr if true, elog otherwise. */ -static void +void AllocSetStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr) @@ -1363,13 +1373,21 @@ AllocSetStats(MemoryContext context, } for (fidx = 0; fidx < ALLOCSET_NUM_FREELISTS; fidx++) { - AllocChunk chunk; + MemoryChunk *chunk = set->freelist[fidx]; - for (chunk = set->freelist[fidx]; chunk != NULL; - chunk = (AllocChunk) chunk->aset) + while (chunk != NULL) { + Size chksz = MemoryChunkGetSize(chunk); + AllocFreelistLink *link = GetFreeListLink(chunk, chksz); + + Assert(((1 << ALLOC_MINBITS) << fidx) == chksz); + freechunks++; - freespace += chunk->size + ALLOC_CHUNKHDRSZ; + freespace += chksz + ALLOC_CHUNKHDRSZ; + + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + chunk = link->next; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); } } @@ -1404,7 +1422,7 @@ AllocSetStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void AllocSetCheck(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -1421,6 +1439,7 @@ AllocSetCheck(MemoryContext context) long blk_used = block->freeptr - bpoz; long blk_data = 0; long nchunks = 0; + bool has_external_chunk = false; if (set->keeper == block) total_allocated += block->endptr - ((char *) set); @@ -1452,14 +1471,25 @@ AllocSetCheck(MemoryContext context) */ while (bpoz < block->freeptr) { - AllocChunk chunk = (AllocChunk) bpoz; + MemoryChunk *chunk = (MemoryChunk *) bpoz; + AllocBlock chunkblock; Size chsize, dsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - chsize = chunk->size; /* aligned chunk size */ + if (MemoryChunkIsExternal(chunk)) + { + chsize = block->endptr - (char *) MemoryChunkGetPointer(chunk); /* aligned chunk size */ + chunkblock = ExternalChunkGetBlock(chunk); + has_external_chunk = true; + } + else + { + chsize = MemoryChunkGetSize(chunk); /* aligned chunk size */ + chunkblock = (AllocBlock) MemoryChunkGetBlock(chunk); + } dsize = chunk->requested_size; /* real data */ /* @@ -1478,20 +1508,15 @@ AllocSetCheck(MemoryContext context) elog(WARNING, "problem in alloc set %s: bad single-chunk %p in block %p", name, chunk, block); - /* - * If chunk is allocated, check for correct aset pointer. (If it's - * free, the aset is the freelist pointer, which we can't check as - * easily...) Note this is an incomplete test, since palloc(0) - * produces an allocated chunk with requested_size == 0. - */ - if (dsize > 0 && chunk->aset != (void *) set) - elog(WARNING, "problem in alloc set %s: bogus aset link in block %p, chunk %p", - name, block, chunk); + /* Check the block offset correctly matches this block */ + if (block != chunkblock) + elog(WARNING, "problem in alloc set %s: bad block offset for chunk %p in block %p", + name, chunk, block); /* * Check for overwrite of padding space in an allocated chunk. */ - if (chunk->aset == (void *) set && dsize < chsize && + if (dsize > 0 && dsize < chsize && !sentinel_ok(chunk, ALLOC_CHUNKHDRSZ + dsize)) elog(WARNING, "problem in alloc set %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); @@ -1500,7 +1525,7 @@ AllocSetCheck(MemoryContext context) * If chunk is allocated, disallow external access to private part * of chunk header. */ - if (chunk->aset == (void *) set) + if (dsize > 0) VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); blk_data += chsize; @@ -1512,6 +1537,10 @@ AllocSetCheck(MemoryContext context) if ((blk_data + (nchunks * ALLOC_CHUNKHDRSZ)) != blk_used) elog(WARNING, "problem in alloc set %s: found inconsistent memory block %p", name, block); + + if (has_external_chunk && nchunks > 1) + elog(WARNING, "problem in alloc set %s: external chunk on non-dedicated block %p", + name, block); } Assert(total_allocated == context->mem_allocated); diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index e530e272e0..fdb17a6ceb 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -39,15 +39,16 @@ #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" #define Generation_BLOCKHDRSZ MAXALIGN(sizeof(GenerationBlock)) -#define Generation_CHUNKHDRSZ sizeof(GenerationChunk) +#define Generation_CHUNKHDRSZ sizeof(MemoryChunk) #define Generation_CHUNK_FRACTION 8 typedef struct GenerationBlock GenerationBlock; /* forward reference */ -typedef struct GenerationChunk GenerationChunk; typedef void *GenerationPointer; @@ -89,6 +90,7 @@ typedef struct GenerationContext struct GenerationBlock { dlist_node node; /* doubly-linked list of blocks */ + GenerationContext *context; /* pointer back to the owning context */ Size blksize; /* allocated size of this block */ int nchunks; /* number of chunks in the block */ int nfree; /* number of free chunks */ @@ -97,104 +99,36 @@ struct GenerationBlock }; /* - * GenerationChunk - * The prefix of each piece of memory in a GenerationBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "context" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). We simplify matters for this - * module by requiring sizeof(GenerationChunk) to be maxaligned, and then - * we can ensure things work by adding any required alignment padding before - * the pointer fields. There is a static assertion below that the alignment - * is done correctly. - */ -struct GenerationChunk -{ - /* size is always the size of the usable space in the chunk */ - Size size; -#ifdef MEMORY_CONTEXT_CHECKING - /* when debugging memory usage, also store actual requested size */ - /* this is zero in a free chunk */ - Size requested_size; - -#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T * 2 + SIZEOF_VOID_P * 2) -#else -#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P * 2) -#endif /* MEMORY_CONTEXT_CHECKING */ - - /* ensure proper alignment by adding padding if needed */ -#if (GENERATIONCHUNK_RAWSIZE % MAXIMUM_ALIGNOF) != 0 - char padding[MAXIMUM_ALIGNOF - GENERATIONCHUNK_RAWSIZE % MAXIMUM_ALIGNOF]; -#endif - - GenerationBlock *block; /* block owning this chunk */ - GenerationContext *context; /* owning context, or NULL if freed chunk */ - /* there must not be any padding to reach a MAXALIGN boundary here! */ -}; - -/* - * Only the "context" field should be accessed outside this module. + * Only the "hdrmask" field should be accessed outside this module. * We keep the rest of an allocated chunk's header marked NOACCESS when using * valgrind. But note that freed chunk headers are kept accessible, for * simplicity. */ -#define GENERATIONCHUNK_PRIVATE_LEN offsetof(GenerationChunk, context) - +#define GENERATIONCHUNK_PRIVATE_LEN offsetof(MemoryChunk, hdrmask) /* * GenerationIsValid * True iff set is valid allocation set. */ #define GenerationIsValid(set) PointerIsValid(set) -#define GenerationPointerGetChunk(ptr) \ - ((GenerationChunk *)(((char *)(ptr)) - Generation_CHUNKHDRSZ)) -#define GenerationChunkGetPointer(chk) \ - ((GenerationPointer *)(((char *)(chk)) + Generation_CHUNKHDRSZ)) +/* + * We always store external chunks on a dedicated block. This makes fetching + * the block from an external chunk easy since it's always the first and only + * chunk on the block. + */ +#define ExternalChunkGetBlock(chunk) \ + (GenerationBlock *) ((char *) chunk - Generation_BLOCKHDRSZ) /* Inlined helper functions */ -static inline void GenerationBlockInit(GenerationBlock *block, Size blksize); +static inline void GenerationBlockInit(GenerationContext *context, + GenerationBlock *block, + Size blksize); static inline bool GenerationBlockIsEmpty(GenerationBlock *block); static inline void GenerationBlockMarkEmpty(GenerationBlock *block); static inline Size GenerationBlockFreeBytes(GenerationBlock *block); static inline void GenerationBlockFree(GenerationContext *set, GenerationBlock *block); -/* - * These functions implement the MemoryContext API for Generation contexts. - */ -static void *GenerationAlloc(MemoryContext context, Size size); -static void GenerationFree(MemoryContext context, void *pointer); -static void *GenerationRealloc(MemoryContext context, void *pointer, Size size); -static void GenerationReset(MemoryContext context); -static void GenerationDelete(MemoryContext context); -static Size GenerationGetChunkSpace(MemoryContext context, void *pointer); -static bool GenerationIsEmpty(MemoryContext context); -static void GenerationStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); - -#ifdef MEMORY_CONTEXT_CHECKING -static void GenerationCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for Generation contexts. - */ -static const MemoryContextMethods GenerationMethods = { - GenerationAlloc, - GenerationFree, - GenerationRealloc, - GenerationReset, - GenerationDelete, - GenerationGetChunkSpace, - GenerationIsEmpty, - GenerationStats -#ifdef MEMORY_CONTEXT_CHECKING - ,GenerationCheck -#endif -}; - /* * Public routines @@ -223,17 +157,20 @@ GenerationContextCreate(MemoryContext parent, GenerationContext *set; GenerationBlock *block; - /* Assert we padded GenerationChunk properly */ + /* ensure MemoryChunk's size is properly maxaligned */ StaticAssertStmt(Generation_CHUNKHDRSZ == MAXALIGN(Generation_CHUNKHDRSZ), - "sizeof(GenerationChunk) is not maxaligned"); - StaticAssertStmt(offsetof(GenerationChunk, context) + sizeof(MemoryContext) == - Generation_CHUNKHDRSZ, - "padding calculation in GenerationChunk is wrong"); + "sizeof(MemoryChunk) is not maxaligned"); /* * First, validate allocation parameters. Asserts seem sufficient because * nobody varies their parameters at runtime. We somewhat arbitrarily - * enforce a minimum 1K block size. + * enforce a minimum 1K block size. We restrict the maximum block size to + * MEMORYCHUNK_MAX_BLOCKOFFSET as MemoryChunks are limited to this in + * regards to addressing the offset between the chunk and the block that + * the chunk is stored on. We would be unable to store the offset between + * the chunk and block for any chunks that were beyond + * MEMORYCHUNK_MAX_BLOCKOFFSET bytes into the block if the block was to be + * larger than this. */ Assert(initBlockSize == MAXALIGN(initBlockSize) && initBlockSize >= 1024); @@ -244,6 +181,7 @@ GenerationContextCreate(MemoryContext parent, (minContextSize == MAXALIGN(minContextSize) && minContextSize >= 1024 && minContextSize <= maxBlockSize)); + Assert(maxBlockSize <= MEMORYCHUNK_MAX_BLOCKOFFSET); /* Determine size of initial block */ allocSize = MAXALIGN(sizeof(GenerationContext)) + @@ -278,7 +216,7 @@ GenerationContextCreate(MemoryContext parent, block = (GenerationBlock *) (((char *) set) + MAXALIGN(sizeof(GenerationContext))); /* determine the block size and initialize it */ firstBlockSize = allocSize - MAXALIGN(sizeof(GenerationContext)); - GenerationBlockInit(block, firstBlockSize); + GenerationBlockInit(set, block, firstBlockSize); /* add it to the doubly-linked list of blocks */ dlist_push_head(&set->blocks, &block->node); @@ -302,7 +240,7 @@ GenerationContextCreate(MemoryContext parent, * * Follows similar ideas as AllocSet, see aset.c for details ... */ - set->allocChunkLimit = maxBlockSize; + set->allocChunkLimit = Min(maxBlockSize, MEMORYCHUNK_MAX_CHUNKSIZE); while ((Size) (set->allocChunkLimit + Generation_CHUNKHDRSZ) > (Size) ((Size) (maxBlockSize - Generation_BLOCKHDRSZ) / Generation_CHUNK_FRACTION)) set->allocChunkLimit >>= 1; @@ -310,7 +248,7 @@ GenerationContextCreate(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) set, T_GenerationContext, - &GenerationMethods, + MCTX_GENERATION_ID, parent, name); @@ -326,7 +264,7 @@ GenerationContextCreate(MemoryContext parent, * The code simply frees all the blocks in the context - we don't keep any * keeper blocks or anything like that. */ -static void +void GenerationReset(MemoryContext context) { GenerationContext *set = (GenerationContext *) context; @@ -371,7 +309,7 @@ GenerationReset(MemoryContext context) * GenerationDelete * Free all memory which is allocated in the given context. */ -static void +void GenerationDelete(MemoryContext context) { /* Reset to release all releasable GenerationBlocks */ @@ -393,12 +331,12 @@ GenerationDelete(MemoryContext context) * is marked, as mcxt.c will set it to UNDEFINED. In some paths we will * return space that is marked NOACCESS - GenerationRealloc has to beware! */ -static void * +void * GenerationAlloc(MemoryContext context, Size size) { GenerationContext *set = (GenerationContext *) context; GenerationBlock *block; - GenerationChunk *chunk; + MemoryChunk *chunk; Size chunk_size = MAXALIGN(size); Size required_size = chunk_size + Generation_CHUNKHDRSZ; @@ -414,6 +352,7 @@ GenerationAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; /* block with a single (used) chunk */ + block->context = set; block->blksize = blksize; block->nchunks = 1; block->nfree = 0; @@ -421,33 +360,33 @@ GenerationAlloc(MemoryContext context, Size size) /* the block is completely full */ block->freeptr = block->endptr = ((char *) block) + blksize; - chunk = (GenerationChunk *) (((char *) block) + Generation_BLOCKHDRSZ); - chunk->block = block; - chunk->context = set; - chunk->size = chunk_size; + chunk = (MemoryChunk *) (((char *) block) + Generation_BLOCKHDRSZ); + + /* mark the MemoryChunk as externally managed */ + MemoryChunkSetHdrMaskExternal(chunk, MCTX_GENERATION_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk_size) - set_sentinel(GenerationChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) GenerationChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* add the block to the list of allocated blocks */ dlist_push_head(&set->blocks, &block->node); /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) GenerationChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return GenerationChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -516,7 +455,7 @@ GenerationAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; /* initialize the new block */ - GenerationBlockInit(block, blksize); + GenerationBlockInit(set, block, blksize); /* add it to the doubly-linked list of blocks */ dlist_push_head(&set->blocks, &block->node); @@ -533,7 +472,7 @@ GenerationAlloc(MemoryContext context, Size size) Assert(block != NULL); Assert((block->endptr - block->freeptr) >= Generation_CHUNKHDRSZ + chunk_size); - chunk = (GenerationChunk *) block->freeptr; + chunk = (MemoryChunk *) block->freeptr; /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, Generation_CHUNKHDRSZ); @@ -543,29 +482,26 @@ GenerationAlloc(MemoryContext context, Size size) Assert(block->freeptr <= block->endptr); - chunk->block = block; - chunk->context = set; - chunk->size = chunk_size; - + MemoryChunkSetHdrMask(chunk, block, chunk_size, MCTX_GENERATION_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(GenerationChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) GenerationChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) GenerationChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return GenerationChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -574,8 +510,10 @@ GenerationAlloc(MemoryContext context, Size size) * mem_allocated field. */ static inline void -GenerationBlockInit(GenerationBlock *block, Size blksize) +GenerationBlockInit(GenerationContext *context, GenerationBlock *block, + Size blksize) { + block->context = context; block->blksize = blksize; block->nchunks = 0; block->nfree = 0; @@ -661,33 +599,48 @@ GenerationBlockFree(GenerationContext *set, GenerationBlock *block) * Update number of chunks in the block, and if all chunks in the block * are now free then discard the block. */ -static void -GenerationFree(MemoryContext context, void *pointer) +void +GenerationFree(void *pointer) { - GenerationContext *set = (GenerationContext *) context; - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); GenerationBlock *block; + GenerationContext *set; +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + Size chunksize; +#endif + + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + chunksize = block->endptr - (char *) pointer; +#endif + } + else + { + block = MemoryChunkGetBlock(chunk); +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + chunksize = MemoryChunkGetSize(chunk); +#endif + } /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - block = chunk->block; + set = block->context; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunk->size) + if (chunk->requested_size < chunksize) if (!sentinel_ok(pointer, chunk->requested_size)) elog(WARNING, "detected write past chunk end in %s %p", ((MemoryContext) set)->name, chunk); #endif #ifdef CLOBBER_FREED_MEMORY - wipe_mem(pointer, chunk->size); + wipe_mem(pointer, chunksize); #endif - /* Reset context to NULL in freed chunks */ - chunk->context = NULL; - #ifdef MEMORY_CONTEXT_CHECKING /* Reset requested_size to 0 in freed chunks */ chunk->requested_size = 0; @@ -732,7 +685,7 @@ GenerationFree(MemoryContext context, void *pointer) */ dlist_delete(&block->node); - context->mem_allocated -= block->blksize; + set->header.mem_allocated -= block->blksize; free(block); } @@ -742,18 +695,30 @@ GenerationFree(MemoryContext context, void *pointer) * and discard the old one. The only exception is when the new size fits * into the old chunk - in that case we just update chunk header. */ -static void * -GenerationRealloc(MemoryContext context, void *pointer, Size size) +void * +GenerationRealloc(void *pointer, Size size) { - GenerationContext *set = (GenerationContext *) context; - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationContext *set; + GenerationBlock *block; GenerationPointer newPointer; Size oldsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - oldsize = chunk->size; + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); + oldsize = block->endptr - (char *) pointer; + } + else + { + block = MemoryChunkGetBlock(chunk); + oldsize = MemoryChunkGetSize(chunk); + } + + set = block->context; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ @@ -848,7 +813,7 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) memcpy(newPointer, pointer, oldsize); /* free old chunk */ - GenerationFree((MemoryContext) set, pointer); + GenerationFree(pointer); return newPointer; } @@ -858,23 +823,51 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -GenerationGetChunkSpace(MemoryContext context, void *pointer) +MemoryContext +GenerationGetChunkContext(void *pointer) { - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); - Size result; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationBlock *block; - VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - result = chunk->size + Generation_CHUNKHDRSZ; - VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return result; + if (MemoryChunkIsExternal(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (GenerationBlock *) MemoryChunkGetBlock(chunk); + + return &block->context->header; +} + +/* + * GenerationGetChunkSpace + * Given a currently-allocated chunk, determine the total space + * it occupies (including all memory-allocation overhead). + */ +Size +GenerationGetChunkSpace(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationBlock *block; + Size chunksize; + + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); + chunksize = block->endptr - (char *) pointer; + } + else + { + block = MemoryChunkGetBlock(chunk); + chunksize = MemoryChunkGetSize(chunk); + } + + return Generation_CHUNKHDRSZ + chunksize; } /* * GenerationIsEmpty * Is a GenerationContext empty of any allocated space? */ -static bool +bool GenerationIsEmpty(MemoryContext context) { GenerationContext *set = (GenerationContext *) context; @@ -903,7 +896,7 @@ GenerationIsEmpty(MemoryContext context) * XXX freespace only accounts for empty space at the end of the block, not * space of freed chunks (which is unknown). */ -static void +void GenerationStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr) @@ -961,7 +954,7 @@ GenerationStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void GenerationCheck(MemoryContext context) { GenerationContext *gen = (GenerationContext *) context; @@ -976,6 +969,7 @@ GenerationCheck(MemoryContext context) int nfree, nchunks; char *ptr; + bool has_external_chunk = false; total_allocated += block->blksize; @@ -987,6 +981,11 @@ GenerationCheck(MemoryContext context) elog(WARNING, "problem in Generation %s: number of free chunks %d in block %p exceeds %d allocated", name, block->nfree, block, block->nchunks); + /* check block belongs to the correct context */ + if (block->context != gen) + elog(WARNING, "problem in Generation %s: bogus context link in block %p", + name, block); + /* Now walk through the chunks and count them. */ nfree = 0; nchunks = 0; @@ -994,42 +993,47 @@ GenerationCheck(MemoryContext context) while (ptr < block->freeptr) { - GenerationChunk *chunk = (GenerationChunk *) ptr; + MemoryChunk *chunk = (MemoryChunk *) ptr; + GenerationBlock *chunkblock; + Size chunksize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); + if (MemoryChunkIsExternal(chunk)) + { + chunkblock = ExternalChunkGetBlock(chunk); + chunksize = block->endptr - (char *) MemoryChunkGetPointer(chunk); + has_external_chunk = true; + } + else + { + chunkblock = MemoryChunkGetBlock(chunk); + chunksize = MemoryChunkGetSize(chunk); + } + /* move to the next chunk */ - ptr += (chunk->size + Generation_CHUNKHDRSZ); + ptr += (chunksize + Generation_CHUNKHDRSZ); nchunks += 1; /* chunks have both block and context pointers, so check both */ - if (chunk->block != block) + if (chunkblock != block) elog(WARNING, "problem in Generation %s: bogus block link in block %p, chunk %p", name, block, chunk); - /* - * Check for valid context pointer. Note this is an incomplete - * test, since palloc(0) produces an allocated chunk with - * requested_size == 0. - */ - if ((chunk->requested_size > 0 && chunk->context != gen) || - (chunk->context != gen && chunk->context != NULL)) - elog(WARNING, "problem in Generation %s: bogus context link in block %p, chunk %p", - name, block, chunk); /* now make sure the chunk size is correct */ - if (chunk->size < chunk->requested_size || - chunk->size != MAXALIGN(chunk->size)) + if (chunksize < chunk->requested_size || + chunksize != MAXALIGN(chunksize)) elog(WARNING, "problem in Generation %s: bogus chunk size in block %p, chunk %p", name, block, chunk); /* is chunk allocated? */ - if (chunk->context != NULL) + if (chunk->requested_size > 0) { - /* check sentinel, but only in allocated blocks */ - if (chunk->requested_size < chunk->size && + /* check sentinel */ + if (chunk->requested_size < chunksize && !sentinel_ok(chunk, Generation_CHUNKHDRSZ + chunk->requested_size)) elog(WARNING, "problem in Generation %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); @@ -1041,7 +1045,7 @@ GenerationCheck(MemoryContext context) * If chunk is allocated, disallow external access to private part * of chunk header. */ - if (chunk->context != NULL) + if (chunk->requested_size > 0) VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); } @@ -1056,6 +1060,11 @@ GenerationCheck(MemoryContext context) if (nfree != block->nfree) elog(WARNING, "problem in Generation %s: number of free chunks %d in block %p does not match header %d", name, nfree, block, block->nfree); + + if (has_external_chunk && nchunks > 1) + elog(WARNING, "problem in Generation %s: external chunk on non-dedicated block %p", + name, block); + } Assert(total_allocated == context->mem_allocated); diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index e12be1b9bd..d30209fc1e 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -29,12 +29,54 @@ #include "utils/fmgrprotos.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_internal.h" /***************************************************************************** * GLOBAL MEMORY * *****************************************************************************/ +static const MemoryContextMethods mcxt_methods[] = { + [MCTX_ASET_ID].alloc = AllocSetAlloc, + [MCTX_ASET_ID].free_p = AllocSetFree, + [MCTX_ASET_ID].realloc = AllocSetRealloc, + [MCTX_ASET_ID].reset = AllocSetReset, + [MCTX_ASET_ID].delete_context = AllocSetDelete, + [MCTX_ASET_ID].get_chunk_context = AllocSetGetChunkContext, + [MCTX_ASET_ID].get_chunk_space = AllocSetGetChunkSpace, + [MCTX_ASET_ID].is_empty = AllocSetIsEmpty, + [MCTX_ASET_ID].stats = AllocSetStats, +#ifdef MEMORY_CONTEXT_CHECKING + [MCTX_ASET_ID].check = AllocSetCheck, +#endif + + [MCTX_GENERATION_ID].alloc = GenerationAlloc, + [MCTX_GENERATION_ID].free_p = GenerationFree, + [MCTX_GENERATION_ID].realloc = GenerationRealloc, + [MCTX_GENERATION_ID].reset = GenerationReset, + [MCTX_GENERATION_ID].delete_context = GenerationDelete, + [MCTX_GENERATION_ID].get_chunk_context = GenerationGetChunkContext, + [MCTX_GENERATION_ID].get_chunk_space = GenerationGetChunkSpace, + [MCTX_GENERATION_ID].is_empty = GenerationIsEmpty, + [MCTX_GENERATION_ID].stats = GenerationStats, +#ifdef MEMORY_CONTEXT_CHECKING + [MCTX_GENERATION_ID].check = GenerationCheck, +#endif + + [MCTX_SLAB_ID].alloc = SlabAlloc, + [MCTX_SLAB_ID].free_p = SlabFree, + [MCTX_SLAB_ID].realloc = SlabRealloc, + [MCTX_SLAB_ID].reset = SlabReset, + [MCTX_SLAB_ID].delete_context = SlabDelete, + [MCTX_SLAB_ID].get_chunk_context = SlabGetChunkContext, + [MCTX_SLAB_ID].get_chunk_space = SlabGetChunkSpace, + [MCTX_SLAB_ID].is_empty = SlabIsEmpty, + [MCTX_SLAB_ID].stats = SlabStats +#ifdef MEMORY_CONTEXT_CHECKING + ,[MCTX_SLAB_ID].check = SlabCheck +#endif +}; + /* * CurrentMemoryContext * Default memory context for allocations. @@ -73,6 +115,13 @@ static void MemoryContextStatsPrint(MemoryContext context, void *passthru, #define AssertNotInCriticalSection(context) \ Assert(CritSectionCount == 0 || (context)->allowInCritSection) +/* + * Call the given function in the MemoryContextMethods for the memory context + * type that 'pointer' belongs to. + */ +#define MCXT_METHOD(pointer, method) \ + mcxt_methods[GetMemoryChunkMethodID(pointer)].method + /***************************************************************************** * EXPORTED ROUTINES * @@ -422,6 +471,17 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) context->allowInCritSection = allow; } +/* + * GetMemoryChunkContext + * Given a currently-allocated chunk, determine the MemoryContext that + * the chunk belongs to. + */ +MemoryContext +GetMemoryChunkContext(void *pointer) +{ + return MCXT_METHOD(pointer, get_chunk_context) (pointer); +} + /* * GetMemoryChunkSpace * Given a currently-allocated chunk, determine the total space @@ -433,9 +493,7 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) Size GetMemoryChunkSpace(void *pointer) { - MemoryContext context = GetMemoryChunkContext(pointer); - - return context->methods->get_chunk_space(context, pointer); + return MCXT_METHOD(pointer, get_chunk_space) (pointer); } /* @@ -814,7 +872,7 @@ MemoryContextContains(MemoryContext context, void *pointer) void MemoryContextCreate(MemoryContext node, NodeTag tag, - const MemoryContextMethods *methods, + MemoryContextMethodID method_id, MemoryContext parent, const char *name) { @@ -824,7 +882,7 @@ MemoryContextCreate(MemoryContext node, /* Initialize all standard fields of memory context header */ node->type = tag; node->isReset = true; - node->methods = methods; + node->methods = &mcxt_methods[method_id]; node->parent = parent; node->firstchild = NULL; node->mem_allocated = 0; @@ -1174,9 +1232,11 @@ palloc_extended(Size size, int flags) void pfree(void *pointer) { +#ifdef USE_VALGRIND MemoryContext context = GetMemoryChunkContext(pointer); +#endif - context->methods->free_p(context, pointer); + MCXT_METHOD(pointer, free_p) (pointer); VALGRIND_MEMPOOL_FREE(context, pointer); } @@ -1187,7 +1247,9 @@ pfree(void *pointer) void * repalloc(void *pointer, Size size) { +#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND) MemoryContext context = GetMemoryChunkContext(pointer); +#endif void *ret; if (!AllocSizeIsValid(size)) @@ -1198,9 +1260,11 @@ repalloc(void *pointer, Size size) /* isReset must be false already */ Assert(!context->isReset); - ret = context->methods->realloc(context, pointer, size); + ret = MCXT_METHOD(pointer, realloc) (pointer, size); if (unlikely(ret == NULL)) { + MemoryContext context = GetMemoryChunkContext(pointer); + MemoryContextStats(TopMemoryContext); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), @@ -1257,7 +1321,9 @@ MemoryContextAllocHuge(MemoryContext context, Size size) void * repalloc_huge(void *pointer, Size size) { +#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND) MemoryContext context = GetMemoryChunkContext(pointer); +#endif void *ret; if (!AllocHugeSizeIsValid(size)) @@ -1268,9 +1334,11 @@ repalloc_huge(void *pointer, Size size) /* isReset must be false already */ Assert(!context->isReset); - ret = context->methods->realloc(context, pointer, size); + ret = MCXT_METHOD(pointer, realloc) (pointer, size); if (unlikely(ret == NULL)) { + MemoryContext context = GetMemoryChunkContext(pointer); + MemoryContextStats(TopMemoryContext); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), diff --git a/src/backend/utils/mmgr/slab.c b/src/backend/utils/mmgr/slab.c index 67d97b22e5..ed57d53155 100644 --- a/src/backend/utils/mmgr/slab.c +++ b/src/backend/utils/mmgr/slab.c @@ -55,6 +55,8 @@ #include "lib/ilist.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" /* * SlabContext is a specialized implementation of MemoryContext. @@ -90,75 +92,23 @@ typedef struct SlabBlock dlist_node node; /* doubly-linked list */ int nfree; /* number of free chunks */ int firstFreeChunk; /* index of the first free chunk in the block */ -} SlabBlock; - -/* - * SlabChunk - * The prefix of each piece of memory in a SlabBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "slab" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). Since we support no machines on - * which MAXALIGN is more than twice sizeof(void *), this happens without any - * special hacking in this struct declaration. But there is a static - * assertion below that the alignment is done correctly. - */ -typedef struct SlabChunk -{ - SlabBlock *block; /* block owning this chunk */ SlabContext *slab; /* owning context */ - /* there must not be any padding to reach a MAXALIGN boundary here! */ -} SlabChunk; +} SlabBlock; +#define Slab_CHUNKHDRSZ sizeof(MemoryChunk) #define SlabPointerGetChunk(ptr) \ - ((SlabChunk *)(((char *)(ptr)) - sizeof(SlabChunk))) + ((MemoryChunk *)(((char *)(ptr)) - sizeof(MemoryChunk))) #define SlabChunkGetPointer(chk) \ - ((void *)(((char *)(chk)) + sizeof(SlabChunk))) + ((void *)(((char *)(chk)) + sizeof(MemoryChunk))) #define SlabBlockGetChunk(slab, block, idx) \ - ((SlabChunk *) ((char *) (block) + sizeof(SlabBlock) \ + ((MemoryChunk *) ((char *) (block) + sizeof(SlabBlock) \ + (idx * slab->fullChunkSize))) #define SlabBlockStart(block) \ ((char *) block + sizeof(SlabBlock)) #define SlabChunkIndex(slab, block, chunk) \ (((char *) chunk - SlabBlockStart(block)) / slab->fullChunkSize) -/* - * These functions implement the MemoryContext API for Slab contexts. - */ -static void *SlabAlloc(MemoryContext context, Size size); -static void SlabFree(MemoryContext context, void *pointer); -static void *SlabRealloc(MemoryContext context, void *pointer, Size size); -static void SlabReset(MemoryContext context); -static void SlabDelete(MemoryContext context); -static Size SlabGetChunkSpace(MemoryContext context, void *pointer); -static bool SlabIsEmpty(MemoryContext context); -static void SlabStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); -#ifdef MEMORY_CONTEXT_CHECKING -static void SlabCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for Slab contexts. - */ -static const MemoryContextMethods SlabMethods = { - SlabAlloc, - SlabFree, - SlabRealloc, - SlabReset, - SlabDelete, - SlabGetChunkSpace, - SlabIsEmpty, - SlabStats -#ifdef MEMORY_CONTEXT_CHECKING - ,SlabCheck -#endif -}; - - /* * SlabContextCreate * Create a new Slab context. @@ -168,8 +118,7 @@ static const MemoryContextMethods SlabMethods = { * blockSize: allocation block size * chunkSize: allocation chunk size * - * The chunkSize may not exceed: - * MAXALIGN_DOWN(SIZE_MAX) - MAXALIGN(sizeof(SlabBlock)) - sizeof(SlabChunk) + * The chunkSize may not exceed MEMORYCHUNK_MAX_CHUNKSIZE */ MemoryContext SlabContextCreate(MemoryContext parent, @@ -184,19 +133,14 @@ SlabContextCreate(MemoryContext parent, SlabContext *slab; int i; - /* Assert we padded SlabChunk properly */ - StaticAssertStmt(sizeof(SlabChunk) == MAXALIGN(sizeof(SlabChunk)), - "sizeof(SlabChunk) is not maxaligned"); - StaticAssertStmt(offsetof(SlabChunk, slab) + sizeof(MemoryContext) == - sizeof(SlabChunk), - "padding calculation in SlabChunk is wrong"); + Assert(MAXALIGN(chunkSize) <= MEMORYCHUNK_MAX_CHUNKSIZE); /* Make sure the linked list node fits inside a freed chunk */ if (chunkSize < sizeof(int)) chunkSize = sizeof(int); /* chunk, including SLAB header (both addresses nicely aligned) */ - fullChunkSize = sizeof(SlabChunk) + MAXALIGN(chunkSize); + fullChunkSize = Slab_CHUNKHDRSZ + MAXALIGN(chunkSize); /* Make sure the block can store at least one chunk. */ if (blockSize < fullChunkSize + sizeof(SlabBlock)) @@ -265,7 +209,7 @@ SlabContextCreate(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) slab, T_SlabContext, - &SlabMethods, + MCTX_SLAB_ID, parent, name); @@ -279,7 +223,7 @@ SlabContextCreate(MemoryContext parent, * The code simply frees all the blocks in the context - we don't keep any * keeper blocks or anything like that. */ -static void +void SlabReset(MemoryContext context) { int i; @@ -322,7 +266,7 @@ SlabReset(MemoryContext context) * SlabDelete * Free all memory which is allocated in the given context. */ -static void +void SlabDelete(MemoryContext context) { /* Reset to release all the SlabBlocks */ @@ -336,12 +280,12 @@ SlabDelete(MemoryContext context) * Returns pointer to allocated memory of given size or NULL if * request could not be completed; memory is added to the slab. */ -static void * +void * SlabAlloc(MemoryContext context, Size size) { SlabContext *slab = castNode(SlabContext, context); SlabBlock *block; - SlabChunk *chunk; + MemoryChunk *chunk; int idx; Assert(slab); @@ -370,6 +314,7 @@ SlabAlloc(MemoryContext context, Size size) block->nfree = slab->chunksPerBlock; block->firstFreeChunk = 0; + block->slab = slab; /* * Put all the chunks on a freelist. Walk the chunks and point each @@ -378,7 +323,7 @@ SlabAlloc(MemoryContext context, Size size) for (idx = 0; idx < slab->chunksPerBlock; idx++) { chunk = SlabBlockGetChunk(slab, block, idx); - *(int32 *) SlabChunkGetPointer(chunk) = (idx + 1); + *(int32 *) MemoryChunkGetPointer(chunk) = (idx + 1); } /* @@ -426,8 +371,8 @@ SlabAlloc(MemoryContext context, Size size) * Remove the chunk from the freelist head. The index of the next free * chunk is stored in the chunk itself. */ - VALGRIND_MAKE_MEM_DEFINED(SlabChunkGetPointer(chunk), sizeof(int32)); - block->firstFreeChunk = *(int32 *) SlabChunkGetPointer(chunk); + VALGRIND_MAKE_MEM_DEFINED(MemoryChunkGetPointer(chunk), sizeof(int32)); + block->firstFreeChunk = *(int32 *) MemoryChunkGetPointer(chunk); Assert(block->firstFreeChunk >= 0); Assert(block->firstFreeChunk <= slab->chunksPerBlock); @@ -464,47 +409,47 @@ SlabAlloc(MemoryContext context, Size size) slab->minFreeChunks = 0; /* Prepare to initialize the chunk header. */ - VALGRIND_MAKE_MEM_UNDEFINED(chunk, sizeof(SlabChunk)); - - chunk->block = block; - chunk->slab = slab; + VALGRIND_MAKE_MEM_UNDEFINED(chunk, Slab_CHUNKHDRSZ); + MemoryChunkSetHdrMask(chunk, block, MAXALIGN(slab->chunkSize), + MCTX_SLAB_ID); #ifdef MEMORY_CONTEXT_CHECKING /* slab mark to catch clobber of "unused" space */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) { - set_sentinel(SlabChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); VALGRIND_MAKE_MEM_NOACCESS(((char *) chunk) + - sizeof(SlabChunk) + slab->chunkSize, + Slab_CHUNKHDRSZ + slab->chunkSize, slab->fullChunkSize - - (slab->chunkSize + sizeof(SlabChunk))); + (slab->chunkSize + Slab_CHUNKHDRSZ)); } #endif + #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) SlabChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif Assert(slab->nblocks * slab->blockSize == context->mem_allocated); - return SlabChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * SlabFree * Frees allocated memory; memory is removed from the slab. */ -static void -SlabFree(MemoryContext context, void *pointer) +void +SlabFree(void *pointer) { int idx; - SlabContext *slab = castNode(SlabContext, context); - SlabChunk *chunk = SlabPointerGetChunk(pointer); - SlabBlock *block = chunk->block; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) if (!sentinel_ok(pointer, slab->chunkSize)) elog(WARNING, "detected write past chunk end in %s %p", slab->header.name, chunk); @@ -560,13 +505,13 @@ SlabFree(MemoryContext context, void *pointer) { free(block); slab->nblocks--; - context->mem_allocated -= slab->blockSize; + slab->header.mem_allocated -= slab->blockSize; } else dlist_push_head(&slab->freelist[block->nfree], &block->node); Assert(slab->nblocks >= 0); - Assert(slab->nblocks * slab->blockSize == context->mem_allocated); + Assert(slab->nblocks * slab->blockSize == slab->header.mem_allocated); } /* @@ -582,13 +527,14 @@ SlabFree(MemoryContext context, void *pointer) * rather pointless - Slab is meant for chunks of constant size, and moreover * realloc is usually used to enlarge the chunk. */ -static void * -SlabRealloc(MemoryContext context, void *pointer, Size size) +void * +SlabRealloc(void *pointer, Size size) { - SlabContext *slab = castNode(SlabContext, context); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; Assert(slab); - /* can't do actual realloc with slab, but let's try to be gentle */ if (size == slab->chunkSize) return pointer; @@ -597,15 +543,33 @@ SlabRealloc(MemoryContext context, void *pointer, Size size) return NULL; /* keep compiler quiet */ } +/* + * SlabGetChunkContext + * Return the MemoryContext that 'pointer' belongs to. + */ +MemoryContext +SlabGetChunkContext(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; + + Assert(slab != NULL); + + return &slab->header; +} + /* * SlabGetChunkSpace * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -SlabGetChunkSpace(MemoryContext context, void *pointer) +Size +SlabGetChunkSpace(void *pointer) { - SlabContext *slab = castNode(SlabContext, context); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; Assert(slab); @@ -616,7 +580,7 @@ SlabGetChunkSpace(MemoryContext context, void *pointer) * SlabIsEmpty * Is an Slab empty of any allocated space? */ -static bool +bool SlabIsEmpty(MemoryContext context) { SlabContext *slab = castNode(SlabContext, context); @@ -635,7 +599,7 @@ SlabIsEmpty(MemoryContext context) * totals: if not NULL, add stats about this context into *totals. * print_to_stderr: print stats to stderr if true, elog otherwise. */ -static void +void SlabStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, @@ -697,7 +661,7 @@ SlabStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void SlabCheck(MemoryContext context) { int i; @@ -728,6 +692,11 @@ SlabCheck(MemoryContext context) elog(WARNING, "problem in slab %s: number of free chunks %d in block %p does not match freelist %d", name, block->nfree, block, i); + /* make sure the slab pointer correctly points to this context */ + if (block->slab != slab) + elog(WARNING, "problem in slab %s: bogus slab link in block %p", + name, block); + /* reset the bitmap of free chunks for this block */ memset(slab->freechunks, 0, (slab->chunksPerBlock * sizeof(bool))); idx = block->firstFreeChunk; @@ -742,7 +711,7 @@ SlabCheck(MemoryContext context) nfree = 0; while (idx < slab->chunksPerBlock) { - SlabChunk *chunk; + MemoryChunk *chunk; /* count the chunk as free, add it to the bitmap */ nfree++; @@ -750,8 +719,8 @@ SlabCheck(MemoryContext context) /* read index of the next free chunk */ chunk = SlabBlockGetChunk(slab, block, idx); - VALGRIND_MAKE_MEM_DEFINED(SlabChunkGetPointer(chunk), sizeof(int32)); - idx = *(int32 *) SlabChunkGetPointer(chunk); + VALGRIND_MAKE_MEM_DEFINED(MemoryChunkGetPointer(chunk), sizeof(int32)); + idx = *(int32 *) MemoryChunkGetPointer(chunk); } for (j = 0; j < slab->chunksPerBlock; j++) @@ -759,19 +728,19 @@ SlabCheck(MemoryContext context) /* non-zero bit in the bitmap means chunk the chunk is used */ if (!slab->freechunks[j]) { - SlabChunk *chunk = SlabBlockGetChunk(slab, block, j); - - /* chunks have both block and slab pointers, so check both */ - if (chunk->block != block) + MemoryChunk *chunk = SlabBlockGetChunk(slab, block, j); + SlabBlock *chunkblock = (SlabBlock *) MemoryChunkGetBlock(chunk); + + /* + * check the chunk's blockoffset correctly points back to + * the block + */ + if (chunkblock != block) elog(WARNING, "problem in slab %s: bogus block link in block %p, chunk %p", name, block, chunk); - if (chunk->slab != slab) - elog(WARNING, "problem in slab %s: bogus slab link in block %p, chunk %p", - name, block, chunk); - /* there might be sentinel (thanks to alignment) */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) if (!sentinel_ok(chunk, slab->chunkSize)) elog(WARNING, "problem in slab %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); diff --git a/src/include/nodes/memnodes.h b/src/include/nodes/memnodes.h index 16cd56da6d..63d07358cd 100644 --- a/src/include/nodes/memnodes.h +++ b/src/include/nodes/memnodes.h @@ -59,11 +59,12 @@ typedef struct MemoryContextMethods { void *(*alloc) (MemoryContext context, Size size); /* call this free_p in case someone #define's free() */ - void (*free_p) (MemoryContext context, void *pointer); - void *(*realloc) (MemoryContext context, void *pointer, Size size); + void (*free_p) (void *pointer); + void *(*realloc) (void *pointer, Size size); void (*reset) (MemoryContext context); void (*delete_context) (MemoryContext context); - Size (*get_chunk_space) (MemoryContext context, void *pointer); + MemoryContext (*get_chunk_context) (void *pointer); + Size (*get_chunk_space) (void *pointer); bool (*is_empty) (MemoryContext context); void (*stats) (MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, diff --git a/src/include/utils/memutils.h b/src/include/utils/memutils.h index 495d1af201..244f7bf4ff 100644 --- a/src/include/utils/memutils.h +++ b/src/include/utils/memutils.h @@ -79,6 +79,7 @@ extern void MemoryContextDeleteChildren(MemoryContext context); extern void MemoryContextSetIdentifier(MemoryContext context, const char *id); extern void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent); +extern MemoryContext GetMemoryChunkContext(void *pointer); extern Size GetMemoryChunkSpace(void *pointer); extern MemoryContext MemoryContextGetParent(MemoryContext context); extern bool MemoryContextIsEmpty(MemoryContext context); @@ -98,53 +99,6 @@ extern bool MemoryContextContains(MemoryContext context, void *pointer); #define MemoryContextCopyAndSetIdentifier(cxt, id) \ MemoryContextSetIdentifier(cxt, MemoryContextStrdup(cxt, id)) -/* - * GetMemoryChunkContext - * Given a currently-allocated chunk, determine the context - * it belongs to. - * - * All chunks allocated by any memory context manager are required to be - * preceded by the corresponding MemoryContext stored, without padding, in the - * preceding sizeof(void*) bytes. A currently-allocated chunk must contain a - * backpointer to its owning context. The backpointer is used by pfree() and - * repalloc() to find the context to call. - */ -#ifndef FRONTEND -static inline MemoryContext -GetMemoryChunkContext(void *pointer) -{ - MemoryContext context; - - /* - * Try to detect bogus pointers handed to us, poorly though we can. - * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an - * allocated chunk. - */ - Assert(pointer != NULL); - Assert(pointer == (void *) MAXALIGN(pointer)); - - /* - * OK, it's probably safe to look at the context. - */ - context = *(MemoryContext *) (((char *) pointer) - sizeof(void *)); - - AssertArg(MemoryContextIsValid(context)); - - return context; -} -#endif - -/* - * This routine handles the context-type-independent part of memory - * context creation. It's intended to be called from context-type- - * specific creation routines, and noplace else. - */ -extern void MemoryContextCreate(MemoryContext node, - NodeTag tag, - const MemoryContextMethods *methods, - MemoryContext parent, - const char *name); - extern void HandleLogMemoryContextInterrupt(void); extern void ProcessLogMemoryContextInterrupt(void); diff --git a/src/include/utils/memutils_internal.h b/src/include/utils/memutils_internal.h new file mode 100644 index 0000000000..e10a559726 --- /dev/null +++ b/src/include/utils/memutils_internal.h @@ -0,0 +1,130 @@ +/*------------------------------------------------------------------------- + * + * memutils_internal.h + * This file contains declarations for memory allocation utility + * functions for internal use. + * + * + * Portions Copyright (c) 2022, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/utils/memutils_internal.h + * + *------------------------------------------------------------------------- + */ + +#ifndef MEMUTILS_INTERNAL_H +#define MEMUTILS_INTERNAL_H + +#include "utils/memutils.h" + +extern void *AllocSetAlloc(MemoryContext context, Size size); +extern void AllocSetFree(void *pointer); +extern void *AllocSetRealloc(void *pointer, Size size); +extern void AllocSetReset(MemoryContext context); +extern void AllocSetDelete(MemoryContext context); +extern MemoryContext AllocSetGetChunkContext(void *pointer); +extern Size AllocSetGetChunkSpace(void *pointer); +extern bool AllocSetIsEmpty(MemoryContext context); +extern void AllocSetStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); + +#ifdef MEMORY_CONTEXT_CHECKING +extern void AllocSetCheck(MemoryContext context); +#endif + + +extern void *GenerationAlloc(MemoryContext context, Size size); +extern void GenerationFree(void *pointer); +extern void *GenerationRealloc(void *pointer, Size size); +extern void GenerationReset(MemoryContext context); +extern void GenerationDelete(MemoryContext context); +extern MemoryContext GenerationGetChunkContext(void *pointer); +extern Size GenerationGetChunkSpace(void *pointer); +extern bool GenerationIsEmpty(MemoryContext context); +extern void GenerationStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); + +#ifdef MEMORY_CONTEXT_CHECKING +extern void GenerationCheck(MemoryContext context); +#endif + + +/* + * These functions implement the MemoryContext API for Slab contexts. + */ +extern void *SlabAlloc(MemoryContext context, Size size); +extern void SlabFree(void *pointer); +extern void *SlabRealloc(void *pointer, Size size); +extern void SlabReset(MemoryContext context); +extern void SlabDelete(MemoryContext context); +extern MemoryContext SlabGetChunkContext(void *pointer); +extern Size SlabGetChunkSpace(void *pointer); +extern bool SlabIsEmpty(MemoryContext context); +extern void SlabStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); +#ifdef MEMORY_CONTEXT_CHECKING +extern void SlabCheck(MemoryContext context); +#endif + +/* + * MemoryContextMethodID + * A unique identifier for each MemoryContext implementation which + * indicates the index into the mcxt_methods[] array. See mcxt.c. + */ +typedef enum MemoryContextMethodID +{ + MCTX_ASET_ID, + MCTX_GENERATION_ID, + MCTX_SLAB_ID, +} MemoryContextMethodID; + +/* + * The number of bits that 8-byte memory chunk headers can use to encode the + * MemoryContextMethodID. + */ +#define MEMORY_CONTEXT_METHODID_BITS 3 +/* + * The maximum possible value of for a MemoryContextMethodID and the bitmask + * for binary ANDing out unrelated bits in the 8-byte chunk header. This must + * be set to the maximum value that can be represented by + * MEMORY_CONTEXT_METHODID_BITS bits. + */ +#define MEMORY_CONTEXT_METHODID_MASK 7 + +/* + * This routine handles the context-type-independent part of memory + * context creation. It's intended to be called from context-type- + * specific creation routines, and noplace else. + */ +extern void MemoryContextCreate(MemoryContext node, + NodeTag tag, + MemoryContextMethodID method_id, + MemoryContext parent, + const char *name); + +static inline MemoryContextMethodID +GetMemoryChunkMethodID(void *pointer) +{ + uint64 header; + + /* + * Try to detect bogus pointers handed to us, poorly though we can. + * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an + * allocated chunk. + */ + Assert(pointer != NULL); + Assert(pointer == (void *) MAXALIGN(pointer)); + + header = *((uint64 *) ((char *) pointer - sizeof(uint64))); + + return header & MEMORY_CONTEXT_METHODID_MASK; +} + +#endif /* MEMUTILS_INTERNAL_H */ diff --git a/src/include/utils/memutils_memorychunk.h b/src/include/utils/memutils_memorychunk.h new file mode 100644 index 0000000000..5e9aea0a35 --- /dev/null +++ b/src/include/utils/memutils_memorychunk.h @@ -0,0 +1,210 @@ +/*------------------------------------------------------------------------- + * + * memutils_memorychunk.h + * Here we define a struct named MemoryChunk which implementations of + * MemoryContexts may use as a header for chunks of memory they allocate. + * + * A MemoryChunk provides a lightweight header which a MemoryContext can use + * to store the size of an allocation and a reference back to the block which + * the given chunk is allocated on. + * + * Although MemoryChunks are used by each of our MemoryContexts, future + * implementations may choose to implement their own method for storing chunk + * headers. The only requirement is that the header end with an 8-byte value + * which the least significant 3-bits of are set to the MemoryContextMethodID + * of the given context. + * + * By default, a MemoryChunk is 8 bytes in size, however when + * MEMORY_CONTEXT_CHECKING is defined the header becomes 16 bytes in size due + * to the additional requested_size field. The MemoryContext may use this + * field for whatever they wish, but it is intended to be used for additional + * checks which are only done in MEMORY_CONTEXT_CHECKING builds. + * + * The MemoryChunk contains a uint64 field named 'hdrmask'. This field is + * used to encode 4 separate pieces of information. Starting with the least + * significant bits of 'hdrmask', the bit space is reserved as follows: + * + * 1. 3-bits to indicate the MemoryContextMethodID as defined by + * MEMORY_CONTEXT_METHODID_MASK + * 2. 1-bit to denote an "external" chunk (see below) + * 3. 30-bits for the amount of memory which was reserved for the chunk + * 4. 30-bits for the number of bytes that must be subtracted from the chunk + * to obtain the address of the block that the chunk is stored on. + * + * External chunks must be used when either the chunk size or block offset + * won't fit in the bit space provided for the field. However, MemoryContext + * are free to use external chunks at any time, regardless of the chunk size + * and block offset. Here "external" just means that the MemoryContext itself + * is managing how to determine the block that the MemoryChunk resides on and + * the size of the chunk. External chunks are initialized via the + * MemoryChunkSetExternal() function. The 30-bit values for the chunk size + * and block offset are unused in external chunks. + * + * Interface: + * + * MemoryChunkSetHdrMask: + * Used to set up a non-external MemoryChunk. + * + * MemoryChunkSetHdrMaskExternal: + * Used to set up an externally managed MemoryChunk. + * + * MemoryChunkIsExternal: + * Determine if the given MemoryChunk is externally managed, i.e. + * MemoryChunkSetHdrMaskExternal() was called on the chunk. + * + * MemoryChunkGetSize: + * For non-external chunks, return the size of the chunk as it was set + * in the call to MemoryChunkSetHdrMask. + * + * MemoryChunkGetBlock: + * For non-external chunks, return a pointer to the block as it was set + * in the call to MemoryChunkSetHdrMask. + * + * Also exports: + * MEMORYCHUNK_MAX_CHUNKSIZE + * MEMORYCHUNK_MAX_BLOCKOFFSET + * PointerGetMemoryChunk + * MemoryChunkGetPointer + * + * Portions Copyright (c) 2022, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/utils/memutils_memorychunk.h + * + *------------------------------------------------------------------------- + */ + +#ifndef MEMUTILS_MEMORYCHUNK_H +#define MEMUTILS_MEMORYCHUNK_H + +#include "utils/memutils_internal.h" + + /* + * The maximum size for a memory chunk before it must be externally managed. + * Must be 1 less than a power of 2. + */ +#define MEMORYCHUNK_MAX_CHUNKSIZE 0x3FFFFFFF + +/* + * The maximum distance in bytes that a MemoryChunk can be offset from the + * block that is storing the chunk. Must be 1 less than a power of 2. + */ +#define MEMORYCHUNK_MAX_BLOCKOFFSET 0x3FFFFFFF + +/* define the least significant base-0 bit of each portion of the hdrmask */ +#define MEMORYCHUNK_EXTERNAL_BASEBIT MEMORY_CONTEXT_METHODID_BITS +#define MEMORYCHUNK_CHUNKSIZE_BASEBIT (MEMORYCHUNK_EXTERNAL_BASEBIT + 1) +#define MEMORYCHUNK_BLOCKOFFSET_BASEBIT (MEMORYCHUNK_CHUNKSIZE_BASEBIT + 30) + +typedef struct MemoryChunk +{ +#ifdef MEMORY_CONTEXT_CHECKING + Size requested_size; +#endif + + /* bitfield for storing details about the chunk */ + uint64 hdrmask; /* must be last */ +} MemoryChunk; + +/* Get the MemoryChunk from the pointer */ +#define PointerGetMemoryChunk(p) ((MemoryChunk *) ((char *) (p) - sizeof(MemoryChunk))) +/* Get the pointer from the MemoryChunk */ +#define MemoryChunkGetPointer(c) ((void *) ((char *) (c) + sizeof(MemoryChunk))) + +/* private macros for making the inline functions below more simple */ +#define HdrMaskIsExternal(hdrmask) \ + ((hdrmask) & (1 << MEMORYCHUNK_EXTERNAL_BASEBIT)) +#define HdrMaskChunkSize(hdrmask) \ + (((hdrmask) >> MEMORYCHUNK_CHUNKSIZE_BASEBIT) & MEMORYCHUNK_MAX_CHUNKSIZE) + +/* + * We should have used up all the bits here, so the compiler is likely to + * optimize out the & MEMORYCHUNK_MAX_BLOCKOFFSET. + */ +#define HdrMaskBlockOffset(hdrmask) \ + (((hdrmask) >> MEMORYCHUNK_BLOCKOFFSET_BASEBIT) & MEMORYCHUNK_MAX_BLOCKOFFSET) + +/* + * MemoryChunkSetHdrMask + * Store the given 'block', 'chunk_size' and 'methodid' in the given + * MemoryChunk. + * + * The number of bytes between 'block' and 'chunk' must be <= + * MEMORYCHUNK_MAX_BLOCKOFFSET. + * 'chunk_size' must be <= MEMORYCHUNK_MAX_CHUNKSIZE. + */ +static inline void +MemoryChunkSetHdrMask(MemoryChunk *chunk, void *block, + Size chunk_size, MemoryContextMethodID methodid) +{ + Size blockoffset = (char *) chunk - (char *) block; + + Assert((char *) chunk > (char *) block); + Assert(blockoffset <= MEMORYCHUNK_MAX_BLOCKOFFSET); + Assert(chunk_size <= MEMORYCHUNK_MAX_CHUNKSIZE); + Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK); + + chunk->hdrmask = (blockoffset << MEMORYCHUNK_BLOCKOFFSET_BASEBIT) | + (chunk_size << MEMORYCHUNK_CHUNKSIZE_BASEBIT) | + methodid; +} + +/* + * MemoryChunkSetHdrMaskExternal + * Set 'chunk' as an externally managed chunk. Here we only record the + * MemoryContextMethodID and set the external chunk bit. + */ +static inline void +MemoryChunkSetHdrMaskExternal(MemoryChunk *chunk, + MemoryContextMethodID methodid) +{ + Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK); + + chunk->hdrmask = (1 << MEMORYCHUNK_EXTERNAL_BASEBIT) | methodid; +} + +/* + * MemoryChunkIsExternal + * Return true if 'chunk' is marked as external. + */ +static inline bool +MemoryChunkIsExternal(MemoryChunk *chunk) +{ + return HdrMaskIsExternal(chunk->hdrmask); +} + +/* + * MemoryChunkGetSize + * For non-external chunks, returns the size of the chunk as was set + * in MemoryChunkSetHdrMask. + */ +static inline Size +MemoryChunkGetSize(MemoryChunk *chunk) +{ + Assert(!HdrMaskIsExternal(chunk->hdrmask)); + + return HdrMaskChunkSize(chunk->hdrmask); +} + +/* + * MemoryChunkGetBlock + * For non-external chunks, returns the pointer to the block as was set + * in MemoryChunkSetHdrMask. + */ +static inline void * +MemoryChunkGetBlock(MemoryChunk *chunk) +{ + Assert(!HdrMaskIsExternal(chunk->hdrmask)); + + return (void *) ((char *) chunk - HdrMaskBlockOffset(chunk->hdrmask)); +} + +/* cleanup all internal definitions */ +#undef MEMORYCHUNK_EXTERNAL_BASEBIT +#undef MEMORYCHUNK_CHUNKSIZE_BASEBIT +#undef MEMORYCHUNK_BLOCKOFFSET_BASEBIT +#undef HdrMaskIsExternal +#undef HdrMaskChunkSize +#undef HdrMaskBlockOffset + +#endif /* MEMUTILS_MEMORYCHUNK_H */ diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 35c9f1efce..86057fd1ba 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -57,6 +57,7 @@ AlenState Alias AllocBlock AllocChunk +AllocFreelistLink AllocPointer AllocSet AllocSetContext @@ -1521,12 +1522,14 @@ MemoizeKey MemoizePath MemoizeState MemoizeTuple +MemoryChunk MemoryContext MemoryContextCallback MemoryContextCallbackFunction MemoryContextCounters MemoryContextData MemoryContextMethods +MemoryContextMethodID MemoryStatsPrintFunc MergeAction MergeActionState -- 2.34.1
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-17 13:58  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-08-17 13:58 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

I've spent a bit more time hacking on this patch.

Changes:

1. Changed GetFreeListLink() so that it stores the AllocFreelistLink
at the end of the chunk rather than at the start.
2. Made it so MemoryChunk stores a magic number in the spare 60 bits
of the hdrmask when the chunk is "external".  This is always set but
only verified in assert builds.
3. In aset.c, I'm no longer storing the chunk_size in the hdrmask. I'm
now instead storing the freelist index. I'll explain this below.
4. Various other cleanups.

For #3, I was doing some benchmarking of the patch with a function I
wrote to heavily exercise palloc() and pfree(). When this function is
called to only allocate a small amount of memory at once, I saw a
small regression in the palloc() / pfree() performance for aset.c.  On
looking at profiles, I saw that the code in AllocSetFreeIndex() was
standing out AllocSetFree().  That function uses the __builtin_clz()
intrinsic function which I see on x86-64 uses the "bsr" instruction.
Going by page 104 of [1], it tells me the latency of that instruction
is 4 for my Zen 2 CPU.  I'm not yet sure why the v3 patch appeared
slower than master for this workload.

To make AllocSetFree() faster, I've now changed things so that instead
of storing the chunk size in the hdrmask of the MemoryChunk, I'm now
just storing the freelist index.  The chunk size is always a power of
2 for non-external chunks. It's very cheap to obtain the chunk size
from the freelist index when we need to.  That's just a "sal" or "shl"
instruction, effectively 8 << freelist_idx, both of which have a
latency of 1. This means that AllocSetFreeIndex() is only called in
AllocSetAlloc now.

This changes the performance as follows:

Master:
postgres=# select pg_allocate_memory_test(64, 1024,
20::bigint*1024*1024*1024, 'aset');
Time: 2524.438 ms (00:02.524)

Old patch (v3):
postgres=#  select pg_allocate_memory_test(64, 1024,
20::bigint*1024*1024*1024, 'aset');
Time: 2646.438 ms (00:02.646)

New patch (v4):
postgres=# select pg_allocate_memory_test(64, 1024,
20::bigint*1024*1024*1024, 'aset');
Time: 2296.228 ms (00:02.296)

(about ~10% faster than master)

This function is allocating 64-byte chunks and keeping 1k of them
around at once, but allocating a total of 20GBs of them. I've attached
another patch with that function in it for anyone who wants to check
the performance.

I also tried another round of the pgbench -S workload that I ran
upthread [2] on the v2 patch. Confusingly, even when testing on
0b039e3a8 as I was last week, I'm unable to see that same 10%
performance increase.

Does anyone else want to have a go at taking v4 for a spin to see how
it performs?

David

[1] https://www.agner.org/optimize/instruction_tables.pdf
[2] https://www.postgresql.org/message-id/CAApHDvrrYfcCXfuc_bZ0xsqBP8U62Y0i27agr9Qt-2geE_rv0Q@mail.gmail...

Attachments:

v4-0001-Improve-performance-of-and-reduce-overheads-of-me.patch (text/plain, 103.0K) download From 744906d722371f33d18c2494b1bfec826cd1b2cd Mon Sep 17 00:00:00 2001 From: David Rowley <dgrowley@gmail.com> Date: Thu, 9 Jun 2022 20:09:22 +1200 Subject: [PATCH v4] Improve performance of and reduce overheads of memory management Whenever we palloc a chunk of memory, traditionally, we prefix the returned pointer with a pointer to the memory context to which the chunk belongs. This is required so that we're able to easily determine the owning context when performing operations such as pfree() and repalloc(). For the AllocSet context, prior to this commit we additionally prefixed the pointer to the owning context with the size of the chunk. This made the header 16 bytes in size. This 16-byte overhead was required for all AllocSet allocations regardless of the allocation size. For the generation context, the problem was worse; in addition to the pointer to the owning context and chunk size, we also stored a pointer to the owning block so that we could track the number of freed chunks on a block. The slab allocator had a 16-byte chunk header. The changes being made here reduce the chunk header size down to just 8 bytes for all 3 of our memory context types. For small to medium sized allocations, this significantly increases the number of chunks that we can fit on a given block which results in much more efficient use of memory. Additionally, this commit completely changes the rule that pointers to palloc'd memory must be directly prefixed by a pointer to the owning memory context and instead, we now insist that they're directly prefixed by an 8-byte value where the least significant 3-bits are set to a value to indicate which type of memory context the pointer belongs to. Using those 3 bits as an index (known as MemoryContextMethodID) to a new array which stores the methods for each memory context type, we're now able to pass the pointer given to functions such as pfree() and repalloc() to the function specific to that context implementation to allow them to devise their own methods of finding the memory context which owns the given allocated chunk of memory. The reason we're able to reduce the chunk header down to just 8 bytes is because of the way we make use of the remaining 61 bits of the required 8-byte chunk header. Here we also implement a general-purpose MemoryChunk struct which makes use of those 61 remaining bits to allow the storage of a 30-bit value which the MemoryContext is free to use as it pleases, and also the number of bytes which must be subtracted from the chunk to get a reference to the block that the chunk is stored on (also 30 bits). The 1 additional remaining bit is to denote if the chunk is an "external" chunk or not. External here means that the chunk header does not store the 30-bit value or the block offset. The MemoryContext can use these external chunks at any time, but must use them if any of the two 30-bit fields are not large enough for the value(s) that need to be stored in them. When the chunk is marked as external, it is up to the MemoryContext to devise its own means to determine the block offset. Using 3-bits for the MemoryContextMethodID does mean we're limiting ourselves to only having a maximum of 8 different memory context types. We could reduce the bit space for the 30-bit value a little to make way for more than 3 bits, but it seems like it might be better to do that only if we ever need more than 8 context types. This would only be a problem if some future memory context type which does not use MemoryChunk really couldn't give up any of the 61 remaining bits in the chunk header. With this MemoryChunk, each of our 3 memory context types can quickly obtain a reference to the block any given chunk is located on. AllocSet is able to find the context to which the chunk is owned by first obtaining a reference to the block by subtracting the block offset as is stored in the 'hdrmask' field and then referencing the block's 'aset' field. The Generation context uses the same method, but GenerationBlock did not have a field pointing back to the owning context, so one is added by this commit. In aset.c and generation.c, all allocations larger than allocChunkLimit are stored on dedicated blocks. When there's just a single chunk on a block like this, it's easy to find the block from the chunk, we just subtract the size of the block header from the chunk pointer. The size of these chunks is also known as we store the endptr on the block, so we can just subtract the pointer to the allocated memory from that. Because we can easily find the owning block and the size of the chunk for these dedicated blocks, we just always use external chunks for allocation sizes larger than allocChunkLimit. For geneartion.c, this sidesteps the problem of non-external MemoryChunks being unable to represent chunk sizes >= 1GB. This is less of a problem for aset.c as we store the freelist index in the MemoryChunk's spare 30-bit field. we can easily reverse engineer the chunk size from this when needed. Storing this saves AllocSetFree() from having to make a call to AllocSetFreeIndex() to determine which freelist to put the newly freed chunk on. For the slab allocator, this commit adds a new restriction that slab chunks cannot be >= 1GB in size. If there happened to be any users of slab.c which used chunk sizes this large, they really should be using AllocSet instead. Here we also add a restriction that normal non-dedicated blocks cannot be 1GB or larger. It's now not possible to pass a 'maxBlockSize' >= 1GB during the creation of an AllocSet or Generation context. Allocations can still be larger than 1GB, it's just these will always be on dedicated blocks (which are not restricted to 1GB in size). Author: Andres Freund, David Rowley Discussion: https://postgr.es/m/CAApHDvpjauCRXcgcaL6+e3eqecEHoeRm9D-kcbuvBitgPnW=vw@mail.gmail.com --- src/backend/utils/mmgr/README | 60 ++- src/backend/utils/mmgr/aset.c | 495 ++++++++++++----------- src/backend/utils/mmgr/generation.c | 334 +++++++-------- src/backend/utils/mmgr/mcxt.c | 91 ++++- src/backend/utils/mmgr/slab.c | 197 ++++----- src/include/nodes/memnodes.h | 7 +- src/include/utils/memutils.h | 48 +-- src/include/utils/memutils_internal.h | 130 ++++++ src/include/utils/memutils_memorychunk.h | 231 +++++++++++ src/tools/pgindent/typedefs.list | 3 + 10 files changed, 1014 insertions(+), 582 deletions(-) create mode 100644 src/include/utils/memutils_internal.h create mode 100644 src/include/utils/memutils_memorychunk.h diff --git a/src/backend/utils/mmgr/README b/src/backend/utils/mmgr/README index 221b4bd343..c94194f7d3 100644 --- a/src/backend/utils/mmgr/README +++ b/src/backend/utils/mmgr/README @@ -378,35 +378,55 @@ MemoryContext like the parent and child contexts, and the name of the context. This is essentially an abstract superclass, and the behavior is -determined by the "methods" pointer is its virtual function table -(struct MemoryContextMethods). Specific memory context types will use -derived structs having these fields as their first fields. All the +determined by the "methods" pointer which references which set of +MemoryContextMethods are to be used. Specific memory context types will +use derived structs having these fields as their first fields. All the contexts of a specific type will have methods pointers that point to -the same static table of function pointers. +the corresponding element in the mcxt_methods[] array as defined in mcxt.c. While operations like allocating from and resetting a context take the relevant MemoryContext as a parameter, operations like free and realloc are trickier. To make those work, we require all memory context types to produce allocated chunks that are immediately, -without any padding, preceded by a pointer to the corresponding -MemoryContext. +without any padding, preceded by a uint64 value of which the least +significant 3 bits are set to the owning context's MemoryContextMethodID. +This allows the code to determine the correct MemoryContextMethods to +use by looking up the mcxt_methods[] array using the 3 bits as an index +into that array. If a type of allocator needs additional information about its chunks, like e.g. the size of the allocation, that information can in turn -precede the MemoryContext. This means the only overhead implied by -the memory context mechanism is a pointer to its context, so we're not -constraining context-type designers very much. - -Given this, routines like pfree determine their corresponding context -with an operation like (although that is usually encapsulated in -GetMemoryChunkContext()) - - MemoryContext context = *(MemoryContext*) (((char *) pointer) - sizeof(void *)); - -and then invoke the corresponding method for the context - - context->methods->free_p(pointer); - +either be encoded into the remaining 61 bits of the preceding uint64 value +or if more space is required, additional values may be stored directly prior +to the uint64 value. It is up to the context implementation to manage this. + +Given this, routines like pfree can determine which set of +MemoryContextMethods to call the free_p function for by calling +GetMemoryChunkMethodID() and finding the corresponding MemoryContextMethods +in the mcxt_methods array[]. For convenience, the MCXT_METHOD() macro is +provided, making the code as simple as: + +void +pfree(void *pointer) +{ + MCXT_METHOD(pointer, free_p)(pointer); +} + +All of the current memory contexts make use of the MemoryChunk header type +which is defined in memutils_memorychunk.h. This suits all of the existing +context types well as it makes use of the remaining 61-bits of the uint64 +header to efficiently encode the size of the chunk of memory (or freelist +index, in the case of aset.c) and the number of bytes which must be subtracted +from the chunk in order to obtain a reference to the block that the chunk +belongs to. 30 bits are used for each of these. If more than 30 bits are +required then the memory context must manage that itself. This can be done by +calling the MemoryChunkSetHdrMaskExternal() function on the given chunk. +Currently, each memory context type stores large allocations on dedicated +blocks (which always contain only a single chunk). For these, finding the +block is simple as we know that the chunk must be the first on the given +block, so the block is always at a fixed offset to the chunk. For these, +finding the size of the chunk is also simple as the block always stores an +endptr which we can use to calculate the size of the chunk. More Control Over aset.c Behavior --------------------------------- diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index ec3e264a73..a4e7f06d36 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -49,6 +49,8 @@ #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" /*-------------------- * Chunk freelist k holds chunks of size 1 << (k + ALLOC_MINBITS), @@ -66,7 +68,9 @@ * CAUTION: ALLOC_MINBITS must be large enough so that * 1<<ALLOC_MINBITS is at least MAXALIGN, * or we may fail to align the smallest chunks adequately. - * 8-byte alignment is enough on all currently known machines. + * 8-byte alignment is enough on all currently known machines. This 8-byte + * minimum also allows us to store a pointer to the next freelist item within + * the chunk of memory itself. * * With the current parameters, request sizes up to 8K are treated as chunks, * larger requests go into dedicated blocks. Change ALLOCSET_NUM_FREELISTS @@ -98,10 +102,9 @@ */ #define ALLOC_BLOCKHDRSZ MAXALIGN(sizeof(AllocBlockData)) -#define ALLOC_CHUNKHDRSZ sizeof(struct AllocChunkData) +#define ALLOC_CHUNKHDRSZ sizeof(MemoryChunk) typedef struct AllocBlockData *AllocBlock; /* forward reference */ -typedef struct AllocChunkData *AllocChunk; /* * AllocPointer @@ -109,6 +112,33 @@ typedef struct AllocChunkData *AllocChunk; */ typedef void *AllocPointer; +/* + * AllocFreelistLink + * When pfreeing memory, if we maintain a freelist for the given chunk's + * size then we use a AllocFreelistLink to point to the current item in + * the AllocSetContext's freelist and then set the given freelist element + * to point to the chunk being freed. + */ +typedef struct AllocFreelistLink +{ + MemoryChunk *next; +} AllocFreelistLink; + +/* + * Obtain a AllocFreelistLink for the given chunk. Allocation sizes are + * always at least sizeof(AllocFreelistLink), so we reuse the pointer's memory + * itself to store the freelist link. To make it less likely that any write + * after pfree() bugs corrupt this, we put the link at the very end of the + * allocated chunk. + */ +#define GetFreeListLink(chkptr, chksz) \ + (AllocFreelistLink *) ((char *) (chkptr) + ALLOC_CHUNKHDRSZ + \ + (chksz) - sizeof(AllocFreelistLink)) + +/* Determine the size of the chunk based on the freelist index */ +#define GetChunkSizeFromFreelistIdx(fidx) \ + ((((Size) 1) << ALLOC_MINBITS) << (fidx)) + /* * AllocSetContext is our standard implementation of MemoryContext. * @@ -123,7 +153,7 @@ typedef struct AllocSetContext MemoryContextData header; /* Standard memory-context fields */ /* Info about storage allocated in this context: */ AllocBlock blocks; /* head of list of blocks in this set */ - AllocChunk freelist[ALLOCSET_NUM_FREELISTS]; /* free chunk lists */ + MemoryChunk *freelist[ALLOCSET_NUM_FREELISTS]; /* free chunk lists */ /* Allocation parameters for this context: */ Size initBlockSize; /* initial block size */ Size maxBlockSize; /* maximum block size */ @@ -139,8 +169,8 @@ typedef AllocSetContext *AllocSet; /* * AllocBlock * An AllocBlock is the unit of memory that is obtained by aset.c - * from malloc(). It contains one or more AllocChunks, which are - * the units requested by palloc() and freed by pfree(). AllocChunks + * from malloc(). It contains one or more MemoryChunks, which are + * the units requested by palloc() and freed by pfree(). MemoryChunks * cannot be returned to malloc() individually, instead they are put * on freelists by pfree() and re-used by the next palloc() that has * a matching request size. @@ -158,48 +188,12 @@ typedef struct AllocBlockData } AllocBlockData; /* - * AllocChunk - * The prefix of each piece of memory in an AllocBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "aset" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). We simplify matters for this - * module by requiring sizeof(AllocChunkData) to be maxaligned, and then - * we can ensure things work by adding any required alignment padding before - * the "aset" field. There is a static assertion below that the alignment - * is done correctly. - */ -typedef struct AllocChunkData -{ - /* size is always the size of the usable space in the chunk */ - Size size; -#ifdef MEMORY_CONTEXT_CHECKING - /* when debugging memory usage, also store actual requested size */ - /* this is zero in a free chunk */ - Size requested_size; - -#define ALLOCCHUNK_RAWSIZE (SIZEOF_SIZE_T * 2 + SIZEOF_VOID_P) -#else -#define ALLOCCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P) -#endif /* MEMORY_CONTEXT_CHECKING */ - - /* ensure proper alignment by adding padding if needed */ -#if (ALLOCCHUNK_RAWSIZE % MAXIMUM_ALIGNOF) != 0 - char padding[MAXIMUM_ALIGNOF - ALLOCCHUNK_RAWSIZE % MAXIMUM_ALIGNOF]; -#endif - - /* aset is the owning aset if allocated, or the freelist link if free */ - void *aset; - /* there must not be any padding to reach a MAXALIGN boundary here! */ -} AllocChunkData; - -/* - * Only the "aset" field should be accessed outside this module. + * Only the "hdrmask" field should be accessed outside this module. * We keep the rest of an allocated chunk's header marked NOACCESS when using * valgrind. But note that chunk headers that are in a freelist are kept * accessible, for simplicity. */ -#define ALLOCCHUNK_PRIVATE_LEN offsetof(AllocChunkData, aset) +#define ALLOCCHUNK_PRIVATE_LEN offsetof(MemoryChunk, hdrmask) /* * AllocPointerIsValid @@ -213,10 +207,12 @@ typedef struct AllocChunkData */ #define AllocSetIsValid(set) PointerIsValid(set) -#define AllocPointerGetChunk(ptr) \ - ((AllocChunk)(((char *)(ptr)) - ALLOC_CHUNKHDRSZ)) -#define AllocChunkGetPointer(chk) \ - ((AllocPointer)(((char *)(chk)) + ALLOC_CHUNKHDRSZ)) +/* + * We always store external chunks on a dedicated block. This makes fetching + * the block from an external chunk easy since it's always the first and only + * chunk on the block. + */ +#define ExternalChunkGetBlock(chunk) (AllocBlock) ((char *) chunk - ALLOC_BLOCKHDRSZ) /* * Rather than repeatedly creating and deleting memory contexts, we keep some @@ -260,42 +256,6 @@ static AllocSetFreeList context_freelists[2] = } }; -/* - * These functions implement the MemoryContext API for AllocSet contexts. - */ -static void *AllocSetAlloc(MemoryContext context, Size size); -static void AllocSetFree(MemoryContext context, void *pointer); -static void *AllocSetRealloc(MemoryContext context, void *pointer, Size size); -static void AllocSetReset(MemoryContext context); -static void AllocSetDelete(MemoryContext context); -static Size AllocSetGetChunkSpace(MemoryContext context, void *pointer); -static bool AllocSetIsEmpty(MemoryContext context); -static void AllocSetStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); - -#ifdef MEMORY_CONTEXT_CHECKING -static void AllocSetCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for AllocSet contexts. - */ -static const MemoryContextMethods AllocSetMethods = { - AllocSetAlloc, - AllocSetFree, - AllocSetRealloc, - AllocSetReset, - AllocSetDelete, - AllocSetGetChunkSpace, - AllocSetIsEmpty, - AllocSetStats -#ifdef MEMORY_CONTEXT_CHECKING - ,AllocSetCheck -#endif -}; - /* ---------- * AllocSetFreeIndex - @@ -387,18 +347,24 @@ AllocSetContextCreateInternal(MemoryContext parent, AllocSet set; AllocBlock block; - /* Assert we padded AllocChunkData properly */ + /* ensure MemoryChunk's size is properly maxaligned */ StaticAssertStmt(ALLOC_CHUNKHDRSZ == MAXALIGN(ALLOC_CHUNKHDRSZ), - "sizeof(AllocChunkData) is not maxaligned"); - StaticAssertStmt(offsetof(AllocChunkData, aset) + sizeof(MemoryContext) == - ALLOC_CHUNKHDRSZ, - "padding calculation in AllocChunkData is wrong"); + "sizeof(MemoryChunk) is not maxaligned"); + /* check we have enough space to store the freelist link */ + StaticAssertStmt(sizeof(AllocFreelistLink) <= (1 << ALLOC_MINBITS), + "sizeof(AllocFreelistLink) larger than minimum allocation size"); /* * First, validate allocation parameters. Once these were regular runtime * test and elog's, but in practice Asserts seem sufficient because nobody * varies their parameters at runtime. We somewhat arbitrarily enforce a - * minimum 1K block size. + * minimum 1K block size. We restrict the maximum block size to + * MEMORYCHUNK_MAX_BLOCKOFFSET as MemoryChunks are limited to this in + * regards to addressing the offset between the chunk and the block that + * the chunk is stored on. We would be unable to store the offset between + * the chunk and block for any chunks that were beyond + * MEMORYCHUNK_MAX_BLOCKOFFSET bytes into the block if the block was to be + * larger than this. */ Assert(initBlockSize == MAXALIGN(initBlockSize) && initBlockSize >= 1024); @@ -409,6 +375,7 @@ AllocSetContextCreateInternal(MemoryContext parent, (minContextSize == MAXALIGN(minContextSize) && minContextSize >= 1024 && minContextSize <= maxBlockSize)); + Assert(maxBlockSize <= MEMORYCHUNK_MAX_BLOCKOFFSET); /* * Check whether the parameters match either available freelist. We do @@ -443,7 +410,7 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Reinitialize its header, installing correct name and parent */ MemoryContextCreate((MemoryContext) set, T_AllocSetContext, - &AllocSetMethods, + MCTX_ASET_ID, parent, name); @@ -519,7 +486,8 @@ AllocSetContextCreateInternal(MemoryContext parent, * * We have to have allocChunkLimit a power of two, because the requested * and actually-allocated sizes of any chunk must be on the same side of - * the limit, else we get confused about whether the chunk is "big". + * the limit, else we get confused about whether the chunk is on a + * dedicated block. * * Also, allocChunkLimit must not exceed ALLOCSET_SEPARATE_THRESHOLD. */ @@ -534,7 +502,7 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) set, T_AllocSetContext, - &AllocSetMethods, + MCTX_ASET_ID, parent, name); @@ -555,7 +523,7 @@ AllocSetContextCreateInternal(MemoryContext parent, * thrash malloc() when a context is repeatedly reset after small allocations, * which is typical behavior for per-tuple contexts. */ -static void +void AllocSetReset(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -623,7 +591,7 @@ AllocSetReset(MemoryContext context) * * Unlike AllocSetReset, this *must* free all resources of the set. */ -static void +void AllocSetDelete(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -717,12 +685,12 @@ AllocSetDelete(MemoryContext context) * is marked, as mcxt.c will set it to UNDEFINED. In some paths we will * return space that is marked NOACCESS - AllocSetRealloc has to beware! */ -static void * +void * AllocSetAlloc(MemoryContext context, Size size) { AllocSet set = (AllocSet) context; AllocBlock block; - AllocChunk chunk; + MemoryChunk *chunk; int fidx; Size chunk_size; Size blksize; @@ -746,18 +714,20 @@ AllocSetAlloc(MemoryContext context, Size size) block->aset = set; block->freeptr = block->endptr = ((char *) block) + blksize; - chunk = (AllocChunk) (((char *) block) + ALLOC_BLOCKHDRSZ); - chunk->aset = set; - chunk->size = chunk_size; + chunk = (MemoryChunk *) (((char *) block) + ALLOC_BLOCKHDRSZ); + + /* mark the MemoryChunk as externally managed */ + MemoryChunkSetHdrMaskExternal(chunk, MCTX_ASET_ID); + #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk_size) - set_sentinel(AllocChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* @@ -780,13 +750,13 @@ AllocSetAlloc(MemoryContext context, Size size) } /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -799,37 +769,43 @@ AllocSetAlloc(MemoryContext context, Size size) chunk = set->freelist[fidx]; if (chunk != NULL) { - Assert(chunk->size >= size); + AllocFreelistLink *link; + + Assert(fidx == MemoryChunkGetValue(chunk)); - set->freelist[fidx] = (AllocChunk) chunk->aset; + chunk_size = GetChunkSizeFromFreelistIdx(fidx); + link = GetFreeListLink(chunk, chunk_size); - chunk->aset = (void *) set; + /* pop this chunk off the freelist */ + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + set->freelist[fidx] = link->next; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(AllocChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, - chunk->size - size); + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, + chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * Choose the actual chunk size to allocate. */ - chunk_size = (1 << ALLOC_MINBITS) << fidx; + chunk_size = GetChunkSizeFromFreelistIdx(fidx); Assert(chunk_size >= size); /* @@ -856,6 +832,7 @@ AllocSetAlloc(MemoryContext context, Size size) */ while (availspace >= ((1 << ALLOC_MINBITS) + ALLOC_CHUNKHDRSZ)) { + AllocFreelistLink *link; Size availchunk = availspace - ALLOC_CHUNKHDRSZ; int a_fidx = AllocSetFreeIndex(availchunk); @@ -864,29 +841,34 @@ AllocSetAlloc(MemoryContext context, Size size) * freelist than the one we need to put this chunk on. The * exception is when availchunk is exactly a power of 2. */ - if (availchunk != ((Size) 1 << (a_fidx + ALLOC_MINBITS))) + if (availchunk != GetChunkSizeFromFreelistIdx(a_fidx)) { a_fidx--; Assert(a_fidx >= 0); - availchunk = ((Size) 1 << (a_fidx + ALLOC_MINBITS)); + availchunk = GetChunkSizeFromFreelistIdx(a_fidx); } - chunk = (AllocChunk) (block->freeptr); + chunk = (MemoryChunk *) (block->freeptr); /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, ALLOC_CHUNKHDRSZ); - block->freeptr += (availchunk + ALLOC_CHUNKHDRSZ); availspace -= (availchunk + ALLOC_CHUNKHDRSZ); - chunk->size = availchunk; + /* store the freelist index in the value field */ + MemoryChunkSetHdrMask(chunk, block, a_fidx, MCTX_ASET_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = 0; /* mark it free */ #endif - chunk->aset = (void *) set->freelist[a_fidx]; + /* push this chunk onto the freelist */ + link = GetFreeListLink(chunk, availchunk); + + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + link->next = set->freelist[a_fidx]; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); + set->freelist[a_fidx] = chunk; } - /* Mark that we need to create a new block */ block = NULL; } @@ -954,7 +936,7 @@ AllocSetAlloc(MemoryContext context, Size size) /* * OK, do the allocation */ - chunk = (AllocChunk) (block->freeptr); + chunk = (MemoryChunk *) (block->freeptr); /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, ALLOC_CHUNKHDRSZ); @@ -962,67 +944,68 @@ AllocSetAlloc(MemoryContext context, Size size) block->freeptr += (chunk_size + ALLOC_CHUNKHDRSZ); Assert(block->freeptr <= block->endptr); - chunk->aset = (void *) set; - chunk->size = chunk_size; + /* store the freelist index in the value field */ + MemoryChunkSetHdrMask(chunk, block, fidx, MCTX_ASET_ID); + #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(AllocChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * AllocSetFree * Frees allocated memory; memory is removed from the set. */ -static void -AllocSetFree(MemoryContext context, void *pointer) +void +AllocSetFree(void *pointer) { - AllocSet set = (AllocSet) context; - AllocChunk chunk = AllocPointerGetChunk(pointer); + AllocSet set; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); + if (MemoryChunkIsExternal(chunk)) + { + + AllocBlock block = ExternalChunkGetBlock(chunk); + + set = block->aset; + #ifdef MEMORY_CONTEXT_CHECKING - /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunk->size) - if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", - set->header.name, chunk); + { + Size chunk_size = block->endptr - (char *) pointer; + + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < chunk_size) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); + } #endif - if (chunk->size > set->allocChunkLimit) - { - /* - * Big chunks are certain to have been allocated as single-chunk - * blocks. Just unlink that block and return it to malloc(). - */ - AllocBlock block = (AllocBlock) (((char *) chunk) - ALLOC_BLOCKHDRSZ); /* - * Try to verify that we have a sane block pointer: it should - * reference the correct aset, and freeptr and endptr should point - * just past the chunk. + * Try to verify that we have a sane block pointer, the freeptr should + * match the endptr. */ - if (block->aset != set || - block->freeptr != block->endptr || - block->freeptr != ((char *) block) + - (chunk->size + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) + if (block->freeptr != block->endptr) elog(ERROR, "could not find block containing chunk %p", chunk); /* OK, remove block from aset's list and free it */ @@ -1033,7 +1016,7 @@ AllocSetFree(MemoryContext context, void *pointer) if (block->next) block->next->prev = block->prev; - context->mem_allocated -= block->endptr - ((char *) block); + set->header.mem_allocated -= block->endptr - ((char *) block); #ifdef CLOBBER_FREED_MEMORY wipe_mem(block, block->freeptr - ((char *) block)); @@ -1042,20 +1025,35 @@ AllocSetFree(MemoryContext context, void *pointer) } else { - /* Normal case, put the chunk into appropriate freelist */ - int fidx = AllocSetFreeIndex(chunk->size); + AllocBlock block = MemoryChunkGetBlock(chunk); + int fidx = MemoryChunkGetValue(chunk); + Size chunk_size = GetChunkSizeFromFreelistIdx(fidx); + AllocFreelistLink *link = GetFreeListLink(chunk, chunk_size); + + set = block->aset; - chunk->aset = (void *) set->freelist[fidx]; +#ifdef MEMORY_CONTEXT_CHECKING + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < chunk_size) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); +#endif #ifdef CLOBBER_FREED_MEMORY - wipe_mem(pointer, chunk->size); + wipe_mem(pointer, chunk_size); #endif + /* Normal case, put the chunk into appropriate freelist */ + /* push this chunk onto the top of the freelist for this chunk size */ + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + link->next = set->freelist[fidx]; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); + set->freelist[fidx] = chunk; #ifdef MEMORY_CONTEXT_CHECKING /* Reset requested_size to 0 in chunks that are on freelist */ chunk->requested_size = 0; #endif - set->freelist[fidx] = chunk; } } @@ -1071,57 +1069,48 @@ AllocSetFree(MemoryContext context, void *pointer) * (In principle, we could use VALGRIND_GET_VBITS() to rediscover the old * request size.) */ -static void * -AllocSetRealloc(MemoryContext context, void *pointer, Size size) +void * +AllocSetRealloc(void *pointer, Size size) { - AllocSet set = (AllocSet) context; - AllocChunk chunk = AllocPointerGetChunk(pointer); + AllocBlock block; + AllocSet set; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); Size oldsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - oldsize = chunk->size; - -#ifdef MEMORY_CONTEXT_CHECKING - /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < oldsize) - if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", - set->header.name, chunk); -#endif - - if (oldsize > set->allocChunkLimit) + if (MemoryChunkIsExternal(chunk)) { /* * The chunk must have been allocated as a single-chunk block. Use * realloc() to make the containing block bigger, or smaller, with * minimum space wastage. */ - AllocBlock block = (AllocBlock) (((char *) chunk) - ALLOC_BLOCKHDRSZ); Size chksize; Size blksize; Size oldblksize; + block = ExternalChunkGetBlock(chunk); + oldsize = block->endptr - (char *) pointer; + set = block->aset; + +#ifdef MEMORY_CONTEXT_CHECKING + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < oldsize) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); +#endif + /* - * Try to verify that we have a sane block pointer: it should - * reference the correct aset, and freeptr and endptr should point - * just past the chunk. + * Try to verify that we have a sane block pointer, the freeptr should + * match the endptr. */ - if (block->aset != set || - block->freeptr != block->endptr || - block->freeptr != ((char *) block) + - (oldsize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) + if (block->freeptr != block->endptr) elog(ERROR, "could not find block containing chunk %p", chunk); - /* - * Even if the new request is less than set->allocChunkLimit, we stick - * with the single-chunk block approach. Therefore we need - * chunk->size to be bigger than set->allocChunkLimit, so we don't get - * confused about the chunk's status in future calls. - */ - chksize = Max(size, set->allocChunkLimit + 1); - chksize = MAXALIGN(chksize); + chksize = MAXALIGN(size); /* Do the realloc */ blksize = chksize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ; @@ -1136,21 +1125,20 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) } /* updated separately, not to underflow when (oldblksize > blksize) */ - context->mem_allocated -= oldblksize; - context->mem_allocated += blksize; + set->header.mem_allocated -= oldblksize; + set->header.mem_allocated += blksize; block->freeptr = block->endptr = ((char *) block) + blksize; /* Update pointers since block has likely been moved */ - chunk = (AllocChunk) (((char *) block) + ALLOC_BLOCKHDRSZ); - pointer = AllocChunkGetPointer(chunk); + chunk = (MemoryChunk *) (((char *) block) + ALLOC_BLOCKHDRSZ); + pointer = MemoryChunkGetPointer(chunk); if (block->prev) block->prev->next = block; else set->blocks = block; if (block->next) block->next->prev = block; - chunk->size = chksize; #ifdef MEMORY_CONTEXT_CHECKING #ifdef RANDOMIZE_ALLOCATED_MEMORY @@ -1172,9 +1160,8 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) #endif chunk->requested_size = size; - /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) + if (size < chksize) set_sentinel(pointer, size); #else /* !MEMORY_CONTEXT_CHECKING */ @@ -1195,12 +1182,24 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) return pointer; } + block = MemoryChunkGetBlock(chunk); + oldsize = GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)); + set = block->aset; + +#ifdef MEMORY_CONTEXT_CHECKING + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < oldsize) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); +#endif + /* * Chunk sizes are aligned to power of 2 in AllocSetAlloc(). Maybe the * allocated area already is >= the new size. (In particular, we will * fall out here if the requested size is a decrease.) */ - else if (oldsize >= size) + if (oldsize >= size) { #ifdef MEMORY_CONTEXT_CHECKING Size oldrequest = chunk->requested_size; @@ -1289,34 +1288,59 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) memcpy(newPointer, pointer, oldsize); /* free old chunk */ - AllocSetFree((MemoryContext) set, pointer); + AllocSetFree(pointer); return newPointer; } } +/* + * AllocSetGetChunkContext + * Return the MemoryContext that 'pointer' belongs to. + */ +MemoryContext +AllocSetGetChunkContext(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + AllocBlock block; + AllocSet set; + + if (MemoryChunkIsExternal(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (AllocBlock) MemoryChunkGetBlock(chunk); + + set = block->aset; + + return &set->header; +} + /* * AllocSetGetChunkSpace * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -AllocSetGetChunkSpace(MemoryContext context, void *pointer) +Size +AllocSetGetChunkSpace(void *pointer) { - AllocChunk chunk = AllocPointerGetChunk(pointer); - Size result; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); - VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - result = chunk->size + ALLOC_CHUNKHDRSZ; - VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return result; + if (MemoryChunkIsExternal(chunk)) + { + AllocBlock block = ExternalChunkGetBlock(chunk); + + return block->endptr - (char *) chunk; + } + + return GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)) + + ALLOC_CHUNKHDRSZ; } /* * AllocSetIsEmpty * Is an allocset empty of any allocated space? */ -static bool +bool AllocSetIsEmpty(MemoryContext context) { /* @@ -1339,7 +1363,7 @@ AllocSetIsEmpty(MemoryContext context) * totals: if not NULL, add stats about this context into *totals. * print_to_stderr: print stats to stderr if true, elog otherwise. */ -static void +void AllocSetStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr) @@ -1363,13 +1387,21 @@ AllocSetStats(MemoryContext context, } for (fidx = 0; fidx < ALLOCSET_NUM_FREELISTS; fidx++) { - AllocChunk chunk; + MemoryChunk *chunk = set->freelist[fidx]; - for (chunk = set->freelist[fidx]; chunk != NULL; - chunk = (AllocChunk) chunk->aset) + while (chunk != NULL) { + Size chksz = GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)); + AllocFreelistLink *link = GetFreeListLink(chunk, chksz); + + Assert(GetChunkSizeFromFreelistIdx(fidx) == chksz); + freechunks++; - freespace += chunk->size + ALLOC_CHUNKHDRSZ; + freespace += chksz + ALLOC_CHUNKHDRSZ; + + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + chunk = link->next; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); } } @@ -1404,7 +1436,7 @@ AllocSetStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void AllocSetCheck(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -1421,6 +1453,7 @@ AllocSetCheck(MemoryContext context) long blk_used = block->freeptr - bpoz; long blk_data = 0; long nchunks = 0; + bool has_external_chunk = false; if (set->keeper == block) total_allocated += block->endptr - ((char *) set); @@ -1452,14 +1485,25 @@ AllocSetCheck(MemoryContext context) */ while (bpoz < block->freeptr) { - AllocChunk chunk = (AllocChunk) bpoz; + MemoryChunk *chunk = (MemoryChunk *) bpoz; + AllocBlock chunkblock; Size chsize, dsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - chsize = chunk->size; /* aligned chunk size */ + if (MemoryChunkIsExternal(chunk)) + { + chsize = block->endptr - (char *) MemoryChunkGetPointer(chunk); /* aligned chunk size */ + chunkblock = ExternalChunkGetBlock(chunk); + has_external_chunk = true; + } + else + { + chsize = GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)); /* aligned chunk size */ + chunkblock = (AllocBlock) MemoryChunkGetBlock(chunk); + } dsize = chunk->requested_size; /* real data */ /* @@ -1478,20 +1522,15 @@ AllocSetCheck(MemoryContext context) elog(WARNING, "problem in alloc set %s: bad single-chunk %p in block %p", name, chunk, block); - /* - * If chunk is allocated, check for correct aset pointer. (If it's - * free, the aset is the freelist pointer, which we can't check as - * easily...) Note this is an incomplete test, since palloc(0) - * produces an allocated chunk with requested_size == 0. - */ - if (dsize > 0 && chunk->aset != (void *) set) - elog(WARNING, "problem in alloc set %s: bogus aset link in block %p, chunk %p", - name, block, chunk); + /* Check the block offset correctly matches this block */ + if (block != chunkblock) + elog(WARNING, "problem in alloc set %s: bad block offset for chunk %p in block %p", + name, chunk, block); /* * Check for overwrite of padding space in an allocated chunk. */ - if (chunk->aset == (void *) set && dsize < chsize && + if (dsize > 0 && dsize < chsize && !sentinel_ok(chunk, ALLOC_CHUNKHDRSZ + dsize)) elog(WARNING, "problem in alloc set %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); @@ -1500,7 +1539,7 @@ AllocSetCheck(MemoryContext context) * If chunk is allocated, disallow external access to private part * of chunk header. */ - if (chunk->aset == (void *) set) + if (dsize > 0) VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); blk_data += chsize; @@ -1512,6 +1551,10 @@ AllocSetCheck(MemoryContext context) if ((blk_data + (nchunks * ALLOC_CHUNKHDRSZ)) != blk_used) elog(WARNING, "problem in alloc set %s: found inconsistent memory block %p", name, block); + + if (has_external_chunk && nchunks > 1) + elog(WARNING, "problem in alloc set %s: external chunk on non-dedicated block %p", + name, block); } Assert(total_allocated == context->mem_allocated); diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index e530e272e0..4e50ce31df 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -39,15 +39,16 @@ #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" #define Generation_BLOCKHDRSZ MAXALIGN(sizeof(GenerationBlock)) -#define Generation_CHUNKHDRSZ sizeof(GenerationChunk) +#define Generation_CHUNKHDRSZ sizeof(MemoryChunk) #define Generation_CHUNK_FRACTION 8 typedef struct GenerationBlock GenerationBlock; /* forward reference */ -typedef struct GenerationChunk GenerationChunk; typedef void *GenerationPointer; @@ -89,6 +90,7 @@ typedef struct GenerationContext struct GenerationBlock { dlist_node node; /* doubly-linked list of blocks */ + GenerationContext *context; /* pointer back to the owning context */ Size blksize; /* allocated size of this block */ int nchunks; /* number of chunks in the block */ int nfree; /* number of free chunks */ @@ -97,104 +99,36 @@ struct GenerationBlock }; /* - * GenerationChunk - * The prefix of each piece of memory in a GenerationBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "context" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). We simplify matters for this - * module by requiring sizeof(GenerationChunk) to be maxaligned, and then - * we can ensure things work by adding any required alignment padding before - * the pointer fields. There is a static assertion below that the alignment - * is done correctly. - */ -struct GenerationChunk -{ - /* size is always the size of the usable space in the chunk */ - Size size; -#ifdef MEMORY_CONTEXT_CHECKING - /* when debugging memory usage, also store actual requested size */ - /* this is zero in a free chunk */ - Size requested_size; - -#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T * 2 + SIZEOF_VOID_P * 2) -#else -#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P * 2) -#endif /* MEMORY_CONTEXT_CHECKING */ - - /* ensure proper alignment by adding padding if needed */ -#if (GENERATIONCHUNK_RAWSIZE % MAXIMUM_ALIGNOF) != 0 - char padding[MAXIMUM_ALIGNOF - GENERATIONCHUNK_RAWSIZE % MAXIMUM_ALIGNOF]; -#endif - - GenerationBlock *block; /* block owning this chunk */ - GenerationContext *context; /* owning context, or NULL if freed chunk */ - /* there must not be any padding to reach a MAXALIGN boundary here! */ -}; - -/* - * Only the "context" field should be accessed outside this module. + * Only the "hdrmask" field should be accessed outside this module. * We keep the rest of an allocated chunk's header marked NOACCESS when using * valgrind. But note that freed chunk headers are kept accessible, for * simplicity. */ -#define GENERATIONCHUNK_PRIVATE_LEN offsetof(GenerationChunk, context) - +#define GENERATIONCHUNK_PRIVATE_LEN offsetof(MemoryChunk, hdrmask) /* * GenerationIsValid * True iff set is valid allocation set. */ #define GenerationIsValid(set) PointerIsValid(set) -#define GenerationPointerGetChunk(ptr) \ - ((GenerationChunk *)(((char *)(ptr)) - Generation_CHUNKHDRSZ)) -#define GenerationChunkGetPointer(chk) \ - ((GenerationPointer *)(((char *)(chk)) + Generation_CHUNKHDRSZ)) +/* + * We always store external chunks on a dedicated block. This makes fetching + * the block from an external chunk easy since it's always the first and only + * chunk on the block. + */ +#define ExternalChunkGetBlock(chunk) \ + (GenerationBlock *) ((char *) chunk - Generation_BLOCKHDRSZ) /* Inlined helper functions */ -static inline void GenerationBlockInit(GenerationBlock *block, Size blksize); +static inline void GenerationBlockInit(GenerationContext *context, + GenerationBlock *block, + Size blksize); static inline bool GenerationBlockIsEmpty(GenerationBlock *block); static inline void GenerationBlockMarkEmpty(GenerationBlock *block); static inline Size GenerationBlockFreeBytes(GenerationBlock *block); static inline void GenerationBlockFree(GenerationContext *set, GenerationBlock *block); -/* - * These functions implement the MemoryContext API for Generation contexts. - */ -static void *GenerationAlloc(MemoryContext context, Size size); -static void GenerationFree(MemoryContext context, void *pointer); -static void *GenerationRealloc(MemoryContext context, void *pointer, Size size); -static void GenerationReset(MemoryContext context); -static void GenerationDelete(MemoryContext context); -static Size GenerationGetChunkSpace(MemoryContext context, void *pointer); -static bool GenerationIsEmpty(MemoryContext context); -static void GenerationStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); - -#ifdef MEMORY_CONTEXT_CHECKING -static void GenerationCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for Generation contexts. - */ -static const MemoryContextMethods GenerationMethods = { - GenerationAlloc, - GenerationFree, - GenerationRealloc, - GenerationReset, - GenerationDelete, - GenerationGetChunkSpace, - GenerationIsEmpty, - GenerationStats -#ifdef MEMORY_CONTEXT_CHECKING - ,GenerationCheck -#endif -}; - /* * Public routines @@ -223,17 +157,20 @@ GenerationContextCreate(MemoryContext parent, GenerationContext *set; GenerationBlock *block; - /* Assert we padded GenerationChunk properly */ + /* ensure MemoryChunk's size is properly maxaligned */ StaticAssertStmt(Generation_CHUNKHDRSZ == MAXALIGN(Generation_CHUNKHDRSZ), - "sizeof(GenerationChunk) is not maxaligned"); - StaticAssertStmt(offsetof(GenerationChunk, context) + sizeof(MemoryContext) == - Generation_CHUNKHDRSZ, - "padding calculation in GenerationChunk is wrong"); + "sizeof(MemoryChunk) is not maxaligned"); /* * First, validate allocation parameters. Asserts seem sufficient because * nobody varies their parameters at runtime. We somewhat arbitrarily - * enforce a minimum 1K block size. + * enforce a minimum 1K block size. We restrict the maximum block size to + * MEMORYCHUNK_MAX_BLOCKOFFSET as MemoryChunks are limited to this in + * regards to addressing the offset between the chunk and the block that + * the chunk is stored on. We would be unable to store the offset between + * the chunk and block for any chunks that were beyond + * MEMORYCHUNK_MAX_BLOCKOFFSET bytes into the block if the block was to be + * larger than this. */ Assert(initBlockSize == MAXALIGN(initBlockSize) && initBlockSize >= 1024); @@ -244,6 +181,7 @@ GenerationContextCreate(MemoryContext parent, (minContextSize == MAXALIGN(minContextSize) && minContextSize >= 1024 && minContextSize <= maxBlockSize)); + Assert(maxBlockSize <= MEMORYCHUNK_MAX_BLOCKOFFSET); /* Determine size of initial block */ allocSize = MAXALIGN(sizeof(GenerationContext)) + @@ -278,7 +216,7 @@ GenerationContextCreate(MemoryContext parent, block = (GenerationBlock *) (((char *) set) + MAXALIGN(sizeof(GenerationContext))); /* determine the block size and initialize it */ firstBlockSize = allocSize - MAXALIGN(sizeof(GenerationContext)); - GenerationBlockInit(block, firstBlockSize); + GenerationBlockInit(set, block, firstBlockSize); /* add it to the doubly-linked list of blocks */ dlist_push_head(&set->blocks, &block->node); @@ -300,9 +238,14 @@ GenerationContextCreate(MemoryContext parent, /* * Compute the allocation chunk size limit for this context. * - * Follows similar ideas as AllocSet, see aset.c for details ... + * Limit the maximum size a non-dedicated chunk can be so that we can fit + * at least Generation_CHUNK_FRACTION of chunks this big onto the maximum + * sized block. We must further limit this value so that it's no more + * than MEMORYCHUNK_MAX_VALUE. We're unable to have non-dedicated chunks + * larger than that value as we store the chunk size in the MemoryChunk + * 'value' field in the call to MemoryChunkSetHdrMask(). */ - set->allocChunkLimit = maxBlockSize; + set->allocChunkLimit = Min(maxBlockSize, MEMORYCHUNK_MAX_VALUE); while ((Size) (set->allocChunkLimit + Generation_CHUNKHDRSZ) > (Size) ((Size) (maxBlockSize - Generation_BLOCKHDRSZ) / Generation_CHUNK_FRACTION)) set->allocChunkLimit >>= 1; @@ -310,7 +253,7 @@ GenerationContextCreate(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) set, T_GenerationContext, - &GenerationMethods, + MCTX_GENERATION_ID, parent, name); @@ -326,7 +269,7 @@ GenerationContextCreate(MemoryContext parent, * The code simply frees all the blocks in the context - we don't keep any * keeper blocks or anything like that. */ -static void +void GenerationReset(MemoryContext context) { GenerationContext *set = (GenerationContext *) context; @@ -371,7 +314,7 @@ GenerationReset(MemoryContext context) * GenerationDelete * Free all memory which is allocated in the given context. */ -static void +void GenerationDelete(MemoryContext context) { /* Reset to release all releasable GenerationBlocks */ @@ -393,12 +336,12 @@ GenerationDelete(MemoryContext context) * is marked, as mcxt.c will set it to UNDEFINED. In some paths we will * return space that is marked NOACCESS - GenerationRealloc has to beware! */ -static void * +void * GenerationAlloc(MemoryContext context, Size size) { GenerationContext *set = (GenerationContext *) context; GenerationBlock *block; - GenerationChunk *chunk; + MemoryChunk *chunk; Size chunk_size = MAXALIGN(size); Size required_size = chunk_size + Generation_CHUNKHDRSZ; @@ -414,6 +357,7 @@ GenerationAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; /* block with a single (used) chunk */ + block->context = set; block->blksize = blksize; block->nchunks = 1; block->nfree = 0; @@ -421,33 +365,33 @@ GenerationAlloc(MemoryContext context, Size size) /* the block is completely full */ block->freeptr = block->endptr = ((char *) block) + blksize; - chunk = (GenerationChunk *) (((char *) block) + Generation_BLOCKHDRSZ); - chunk->block = block; - chunk->context = set; - chunk->size = chunk_size; + chunk = (MemoryChunk *) (((char *) block) + Generation_BLOCKHDRSZ); + + /* mark the MemoryChunk as externally managed */ + MemoryChunkSetHdrMaskExternal(chunk, MCTX_GENERATION_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk_size) - set_sentinel(GenerationChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) GenerationChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* add the block to the list of allocated blocks */ dlist_push_head(&set->blocks, &block->node); /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) GenerationChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return GenerationChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -516,7 +460,7 @@ GenerationAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; /* initialize the new block */ - GenerationBlockInit(block, blksize); + GenerationBlockInit(set, block, blksize); /* add it to the doubly-linked list of blocks */ dlist_push_head(&set->blocks, &block->node); @@ -533,7 +477,7 @@ GenerationAlloc(MemoryContext context, Size size) Assert(block != NULL); Assert((block->endptr - block->freeptr) >= Generation_CHUNKHDRSZ + chunk_size); - chunk = (GenerationChunk *) block->freeptr; + chunk = (MemoryChunk *) block->freeptr; /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, Generation_CHUNKHDRSZ); @@ -543,29 +487,26 @@ GenerationAlloc(MemoryContext context, Size size) Assert(block->freeptr <= block->endptr); - chunk->block = block; - chunk->context = set; - chunk->size = chunk_size; - + MemoryChunkSetHdrMask(chunk, block, chunk_size, MCTX_GENERATION_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(GenerationChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) GenerationChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) GenerationChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return GenerationChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -574,8 +515,10 @@ GenerationAlloc(MemoryContext context, Size size) * mem_allocated field. */ static inline void -GenerationBlockInit(GenerationBlock *block, Size blksize) +GenerationBlockInit(GenerationContext *context, GenerationBlock *block, + Size blksize) { + block->context = context; block->blksize = blksize; block->nchunks = 0; block->nfree = 0; @@ -661,33 +604,48 @@ GenerationBlockFree(GenerationContext *set, GenerationBlock *block) * Update number of chunks in the block, and if all chunks in the block * are now free then discard the block. */ -static void -GenerationFree(MemoryContext context, void *pointer) +void +GenerationFree(void *pointer) { - GenerationContext *set = (GenerationContext *) context; - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); GenerationBlock *block; + GenerationContext *set; +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + Size chunksize; +#endif + + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + chunksize = block->endptr - (char *) pointer; +#endif + } + else + { + block = MemoryChunkGetBlock(chunk); +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + chunksize = MemoryChunkGetValue(chunk); +#endif + } /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - block = chunk->block; + set = block->context; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunk->size) + if (chunk->requested_size < chunksize) if (!sentinel_ok(pointer, chunk->requested_size)) elog(WARNING, "detected write past chunk end in %s %p", ((MemoryContext) set)->name, chunk); #endif #ifdef CLOBBER_FREED_MEMORY - wipe_mem(pointer, chunk->size); + wipe_mem(pointer, chunksize); #endif - /* Reset context to NULL in freed chunks */ - chunk->context = NULL; - #ifdef MEMORY_CONTEXT_CHECKING /* Reset requested_size to 0 in freed chunks */ chunk->requested_size = 0; @@ -732,7 +690,7 @@ GenerationFree(MemoryContext context, void *pointer) */ dlist_delete(&block->node); - context->mem_allocated -= block->blksize; + set->header.mem_allocated -= block->blksize; free(block); } @@ -742,18 +700,30 @@ GenerationFree(MemoryContext context, void *pointer) * and discard the old one. The only exception is when the new size fits * into the old chunk - in that case we just update chunk header. */ -static void * -GenerationRealloc(MemoryContext context, void *pointer, Size size) +void * +GenerationRealloc(void *pointer, Size size) { - GenerationContext *set = (GenerationContext *) context; - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationContext *set; + GenerationBlock *block; GenerationPointer newPointer; Size oldsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - oldsize = chunk->size; + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); + oldsize = block->endptr - (char *) pointer; + } + else + { + block = MemoryChunkGetBlock(chunk); + oldsize = MemoryChunkGetValue(chunk); + } + + set = block->context; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ @@ -848,7 +818,7 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) memcpy(newPointer, pointer, oldsize); /* free old chunk */ - GenerationFree((MemoryContext) set, pointer); + GenerationFree(pointer); return newPointer; } @@ -858,23 +828,47 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -GenerationGetChunkSpace(MemoryContext context, void *pointer) +MemoryContext +GenerationGetChunkContext(void *pointer) { - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); - Size result; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationBlock *block; - VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - result = chunk->size + Generation_CHUNKHDRSZ; - VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return result; + if (MemoryChunkIsExternal(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (GenerationBlock *) MemoryChunkGetBlock(chunk); + + return &block->context->header; +} + +/* + * GenerationGetChunkSpace + * Given a currently-allocated chunk, determine the total space + * it occupies (including all memory-allocation overhead). + */ +Size +GenerationGetChunkSpace(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + Size chunksize; + + if (MemoryChunkIsExternal(chunk)) + { + GenerationBlock *block = ExternalChunkGetBlock(chunk); + chunksize = block->endptr - (char *) pointer; + } + else + chunksize = MemoryChunkGetValue(chunk); + + return Generation_CHUNKHDRSZ + chunksize; } /* * GenerationIsEmpty * Is a GenerationContext empty of any allocated space? */ -static bool +bool GenerationIsEmpty(MemoryContext context) { GenerationContext *set = (GenerationContext *) context; @@ -903,7 +897,7 @@ GenerationIsEmpty(MemoryContext context) * XXX freespace only accounts for empty space at the end of the block, not * space of freed chunks (which is unknown). */ -static void +void GenerationStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr) @@ -961,7 +955,7 @@ GenerationStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void GenerationCheck(MemoryContext context) { GenerationContext *gen = (GenerationContext *) context; @@ -976,6 +970,7 @@ GenerationCheck(MemoryContext context) int nfree, nchunks; char *ptr; + bool has_external_chunk = false; total_allocated += block->blksize; @@ -987,6 +982,11 @@ GenerationCheck(MemoryContext context) elog(WARNING, "problem in Generation %s: number of free chunks %d in block %p exceeds %d allocated", name, block->nfree, block, block->nchunks); + /* check block belongs to the correct context */ + if (block->context != gen) + elog(WARNING, "problem in Generation %s: bogus context link in block %p", + name, block); + /* Now walk through the chunks and count them. */ nfree = 0; nchunks = 0; @@ -994,42 +994,47 @@ GenerationCheck(MemoryContext context) while (ptr < block->freeptr) { - GenerationChunk *chunk = (GenerationChunk *) ptr; + MemoryChunk *chunk = (MemoryChunk *) ptr; + GenerationBlock *chunkblock; + Size chunksize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); + if (MemoryChunkIsExternal(chunk)) + { + chunkblock = ExternalChunkGetBlock(chunk); + chunksize = block->endptr - (char *) MemoryChunkGetPointer(chunk); + has_external_chunk = true; + } + else + { + chunkblock = MemoryChunkGetBlock(chunk); + chunksize = MemoryChunkGetValue(chunk); + } + /* move to the next chunk */ - ptr += (chunk->size + Generation_CHUNKHDRSZ); + ptr += (chunksize + Generation_CHUNKHDRSZ); nchunks += 1; /* chunks have both block and context pointers, so check both */ - if (chunk->block != block) + if (chunkblock != block) elog(WARNING, "problem in Generation %s: bogus block link in block %p, chunk %p", name, block, chunk); - /* - * Check for valid context pointer. Note this is an incomplete - * test, since palloc(0) produces an allocated chunk with - * requested_size == 0. - */ - if ((chunk->requested_size > 0 && chunk->context != gen) || - (chunk->context != gen && chunk->context != NULL)) - elog(WARNING, "problem in Generation %s: bogus context link in block %p, chunk %p", - name, block, chunk); /* now make sure the chunk size is correct */ - if (chunk->size < chunk->requested_size || - chunk->size != MAXALIGN(chunk->size)) + if (chunksize < chunk->requested_size || + chunksize != MAXALIGN(chunksize)) elog(WARNING, "problem in Generation %s: bogus chunk size in block %p, chunk %p", name, block, chunk); /* is chunk allocated? */ - if (chunk->context != NULL) + if (chunk->requested_size > 0) { - /* check sentinel, but only in allocated blocks */ - if (chunk->requested_size < chunk->size && + /* check sentinel */ + if (chunk->requested_size < chunksize && !sentinel_ok(chunk, Generation_CHUNKHDRSZ + chunk->requested_size)) elog(WARNING, "problem in Generation %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); @@ -1041,7 +1046,7 @@ GenerationCheck(MemoryContext context) * If chunk is allocated, disallow external access to private part * of chunk header. */ - if (chunk->context != NULL) + if (chunk->requested_size > 0) VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); } @@ -1056,6 +1061,11 @@ GenerationCheck(MemoryContext context) if (nfree != block->nfree) elog(WARNING, "problem in Generation %s: number of free chunks %d in block %p does not match header %d", name, nfree, block, block->nfree); + + if (has_external_chunk && nchunks > 1) + elog(WARNING, "problem in Generation %s: external chunk on non-dedicated block %p", + name, block); + } Assert(total_allocated == context->mem_allocated); diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index e12be1b9bd..7c53222b9d 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -29,12 +29,57 @@ #include "utils/fmgrprotos.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_internal.h" /***************************************************************************** * GLOBAL MEMORY * *****************************************************************************/ +static const MemoryContextMethods mcxt_methods[] = { + /* aset.c */ + [MCTX_ASET_ID].alloc = AllocSetAlloc, + [MCTX_ASET_ID].free_p = AllocSetFree, + [MCTX_ASET_ID].realloc = AllocSetRealloc, + [MCTX_ASET_ID].reset = AllocSetReset, + [MCTX_ASET_ID].delete_context = AllocSetDelete, + [MCTX_ASET_ID].get_chunk_context = AllocSetGetChunkContext, + [MCTX_ASET_ID].get_chunk_space = AllocSetGetChunkSpace, + [MCTX_ASET_ID].is_empty = AllocSetIsEmpty, + [MCTX_ASET_ID].stats = AllocSetStats, +#ifdef MEMORY_CONTEXT_CHECKING + [MCTX_ASET_ID].check = AllocSetCheck, +#endif + + /* generation.c */ + [MCTX_GENERATION_ID].alloc = GenerationAlloc, + [MCTX_GENERATION_ID].free_p = GenerationFree, + [MCTX_GENERATION_ID].realloc = GenerationRealloc, + [MCTX_GENERATION_ID].reset = GenerationReset, + [MCTX_GENERATION_ID].delete_context = GenerationDelete, + [MCTX_GENERATION_ID].get_chunk_context = GenerationGetChunkContext, + [MCTX_GENERATION_ID].get_chunk_space = GenerationGetChunkSpace, + [MCTX_GENERATION_ID].is_empty = GenerationIsEmpty, + [MCTX_GENERATION_ID].stats = GenerationStats, +#ifdef MEMORY_CONTEXT_CHECKING + [MCTX_GENERATION_ID].check = GenerationCheck, +#endif + + /* slab.c */ + [MCTX_SLAB_ID].alloc = SlabAlloc, + [MCTX_SLAB_ID].free_p = SlabFree, + [MCTX_SLAB_ID].realloc = SlabRealloc, + [MCTX_SLAB_ID].reset = SlabReset, + [MCTX_SLAB_ID].delete_context = SlabDelete, + [MCTX_SLAB_ID].get_chunk_context = SlabGetChunkContext, + [MCTX_SLAB_ID].get_chunk_space = SlabGetChunkSpace, + [MCTX_SLAB_ID].is_empty = SlabIsEmpty, + [MCTX_SLAB_ID].stats = SlabStats +#ifdef MEMORY_CONTEXT_CHECKING + ,[MCTX_SLAB_ID].check = SlabCheck +#endif +}; + /* * CurrentMemoryContext * Default memory context for allocations. @@ -73,6 +118,13 @@ static void MemoryContextStatsPrint(MemoryContext context, void *passthru, #define AssertNotInCriticalSection(context) \ Assert(CritSectionCount == 0 || (context)->allowInCritSection) +/* + * Call the given function in the MemoryContextMethods for the memory context + * type that 'pointer' belongs to. + */ +#define MCXT_METHOD(pointer, method) \ + mcxt_methods[GetMemoryChunkMethodID(pointer)].method + /***************************************************************************** * EXPORTED ROUTINES * @@ -422,6 +474,17 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) context->allowInCritSection = allow; } +/* + * GetMemoryChunkContext + * Given a currently-allocated chunk, determine the MemoryContext that + * the chunk belongs to. + */ +MemoryContext +GetMemoryChunkContext(void *pointer) +{ + return MCXT_METHOD(pointer, get_chunk_context) (pointer); +} + /* * GetMemoryChunkSpace * Given a currently-allocated chunk, determine the total space @@ -433,9 +496,7 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) Size GetMemoryChunkSpace(void *pointer) { - MemoryContext context = GetMemoryChunkContext(pointer); - - return context->methods->get_chunk_space(context, pointer); + return MCXT_METHOD(pointer, get_chunk_space) (pointer); } /* @@ -814,7 +875,7 @@ MemoryContextContains(MemoryContext context, void *pointer) void MemoryContextCreate(MemoryContext node, NodeTag tag, - const MemoryContextMethods *methods, + MemoryContextMethodID method_id, MemoryContext parent, const char *name) { @@ -824,7 +885,7 @@ MemoryContextCreate(MemoryContext node, /* Initialize all standard fields of memory context header */ node->type = tag; node->isReset = true; - node->methods = methods; + node->methods = &mcxt_methods[method_id]; node->parent = parent; node->firstchild = NULL; node->mem_allocated = 0; @@ -1174,9 +1235,11 @@ palloc_extended(Size size, int flags) void pfree(void *pointer) { +#ifdef USE_VALGRIND MemoryContext context = GetMemoryChunkContext(pointer); +#endif - context->methods->free_p(context, pointer); + MCXT_METHOD(pointer, free_p) (pointer); VALGRIND_MEMPOOL_FREE(context, pointer); } @@ -1187,7 +1250,9 @@ pfree(void *pointer) void * repalloc(void *pointer, Size size) { +#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND) MemoryContext context = GetMemoryChunkContext(pointer); +#endif void *ret; if (!AllocSizeIsValid(size)) @@ -1198,15 +1263,17 @@ repalloc(void *pointer, Size size) /* isReset must be false already */ Assert(!context->isReset); - ret = context->methods->realloc(context, pointer, size); + ret = MCXT_METHOD(pointer, realloc) (pointer, size); if (unlikely(ret == NULL)) { + MemoryContext cxt = GetMemoryChunkContext(pointer); + MemoryContextStats(TopMemoryContext); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"), errdetail("Failed on request of size %zu in memory context \"%s\".", - size, context->name))); + size, cxt->name))); } VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size); @@ -1257,7 +1324,9 @@ MemoryContextAllocHuge(MemoryContext context, Size size) void * repalloc_huge(void *pointer, Size size) { +#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND) MemoryContext context = GetMemoryChunkContext(pointer); +#endif void *ret; if (!AllocHugeSizeIsValid(size)) @@ -1268,15 +1337,17 @@ repalloc_huge(void *pointer, Size size) /* isReset must be false already */ Assert(!context->isReset); - ret = context->methods->realloc(context, pointer, size); + ret = MCXT_METHOD(pointer, realloc) (pointer, size); if (unlikely(ret == NULL)) { + MemoryContext cxt = GetMemoryChunkContext(pointer); + MemoryContextStats(TopMemoryContext); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"), errdetail("Failed on request of size %zu in memory context \"%s\".", - size, context->name))); + size, cxt->name))); } VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size); diff --git a/src/backend/utils/mmgr/slab.c b/src/backend/utils/mmgr/slab.c index 67d97b22e5..e042e596f7 100644 --- a/src/backend/utils/mmgr/slab.c +++ b/src/backend/utils/mmgr/slab.c @@ -55,6 +55,8 @@ #include "lib/ilist.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" /* * SlabContext is a specialized implementation of MemoryContext. @@ -90,75 +92,23 @@ typedef struct SlabBlock dlist_node node; /* doubly-linked list */ int nfree; /* number of free chunks */ int firstFreeChunk; /* index of the first free chunk in the block */ -} SlabBlock; - -/* - * SlabChunk - * The prefix of each piece of memory in a SlabBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "slab" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). Since we support no machines on - * which MAXALIGN is more than twice sizeof(void *), this happens without any - * special hacking in this struct declaration. But there is a static - * assertion below that the alignment is done correctly. - */ -typedef struct SlabChunk -{ - SlabBlock *block; /* block owning this chunk */ SlabContext *slab; /* owning context */ - /* there must not be any padding to reach a MAXALIGN boundary here! */ -} SlabChunk; +} SlabBlock; +#define Slab_CHUNKHDRSZ sizeof(MemoryChunk) #define SlabPointerGetChunk(ptr) \ - ((SlabChunk *)(((char *)(ptr)) - sizeof(SlabChunk))) + ((MemoryChunk *)(((char *)(ptr)) - sizeof(MemoryChunk))) #define SlabChunkGetPointer(chk) \ - ((void *)(((char *)(chk)) + sizeof(SlabChunk))) + ((void *)(((char *)(chk)) + sizeof(MemoryChunk))) #define SlabBlockGetChunk(slab, block, idx) \ - ((SlabChunk *) ((char *) (block) + sizeof(SlabBlock) \ + ((MemoryChunk *) ((char *) (block) + sizeof(SlabBlock) \ + (idx * slab->fullChunkSize))) #define SlabBlockStart(block) \ ((char *) block + sizeof(SlabBlock)) #define SlabChunkIndex(slab, block, chunk) \ (((char *) chunk - SlabBlockStart(block)) / slab->fullChunkSize) -/* - * These functions implement the MemoryContext API for Slab contexts. - */ -static void *SlabAlloc(MemoryContext context, Size size); -static void SlabFree(MemoryContext context, void *pointer); -static void *SlabRealloc(MemoryContext context, void *pointer, Size size); -static void SlabReset(MemoryContext context); -static void SlabDelete(MemoryContext context); -static Size SlabGetChunkSpace(MemoryContext context, void *pointer); -static bool SlabIsEmpty(MemoryContext context); -static void SlabStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); -#ifdef MEMORY_CONTEXT_CHECKING -static void SlabCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for Slab contexts. - */ -static const MemoryContextMethods SlabMethods = { - SlabAlloc, - SlabFree, - SlabRealloc, - SlabReset, - SlabDelete, - SlabGetChunkSpace, - SlabIsEmpty, - SlabStats -#ifdef MEMORY_CONTEXT_CHECKING - ,SlabCheck -#endif -}; - - /* * SlabContextCreate * Create a new Slab context. @@ -168,8 +118,7 @@ static const MemoryContextMethods SlabMethods = { * blockSize: allocation block size * chunkSize: allocation chunk size * - * The chunkSize may not exceed: - * MAXALIGN_DOWN(SIZE_MAX) - MAXALIGN(sizeof(SlabBlock)) - sizeof(SlabChunk) + * The MAXALIGN(chunkSize) may not exceed MEMORYCHUNK_MAX_VALUE */ MemoryContext SlabContextCreate(MemoryContext parent, @@ -184,19 +133,14 @@ SlabContextCreate(MemoryContext parent, SlabContext *slab; int i; - /* Assert we padded SlabChunk properly */ - StaticAssertStmt(sizeof(SlabChunk) == MAXALIGN(sizeof(SlabChunk)), - "sizeof(SlabChunk) is not maxaligned"); - StaticAssertStmt(offsetof(SlabChunk, slab) + sizeof(MemoryContext) == - sizeof(SlabChunk), - "padding calculation in SlabChunk is wrong"); + Assert(MAXALIGN(chunkSize) <= MEMORYCHUNK_MAX_VALUE); /* Make sure the linked list node fits inside a freed chunk */ if (chunkSize < sizeof(int)) chunkSize = sizeof(int); /* chunk, including SLAB header (both addresses nicely aligned) */ - fullChunkSize = sizeof(SlabChunk) + MAXALIGN(chunkSize); + fullChunkSize = Slab_CHUNKHDRSZ + MAXALIGN(chunkSize); /* Make sure the block can store at least one chunk. */ if (blockSize < fullChunkSize + sizeof(SlabBlock)) @@ -265,7 +209,7 @@ SlabContextCreate(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) slab, T_SlabContext, - &SlabMethods, + MCTX_SLAB_ID, parent, name); @@ -279,7 +223,7 @@ SlabContextCreate(MemoryContext parent, * The code simply frees all the blocks in the context - we don't keep any * keeper blocks or anything like that. */ -static void +void SlabReset(MemoryContext context) { int i; @@ -322,7 +266,7 @@ SlabReset(MemoryContext context) * SlabDelete * Free all memory which is allocated in the given context. */ -static void +void SlabDelete(MemoryContext context) { /* Reset to release all the SlabBlocks */ @@ -336,12 +280,12 @@ SlabDelete(MemoryContext context) * Returns pointer to allocated memory of given size or NULL if * request could not be completed; memory is added to the slab. */ -static void * +void * SlabAlloc(MemoryContext context, Size size) { SlabContext *slab = castNode(SlabContext, context); SlabBlock *block; - SlabChunk *chunk; + MemoryChunk *chunk; int idx; Assert(slab); @@ -370,6 +314,7 @@ SlabAlloc(MemoryContext context, Size size) block->nfree = slab->chunksPerBlock; block->firstFreeChunk = 0; + block->slab = slab; /* * Put all the chunks on a freelist. Walk the chunks and point each @@ -378,7 +323,7 @@ SlabAlloc(MemoryContext context, Size size) for (idx = 0; idx < slab->chunksPerBlock; idx++) { chunk = SlabBlockGetChunk(slab, block, idx); - *(int32 *) SlabChunkGetPointer(chunk) = (idx + 1); + *(int32 *) MemoryChunkGetPointer(chunk) = (idx + 1); } /* @@ -426,8 +371,8 @@ SlabAlloc(MemoryContext context, Size size) * Remove the chunk from the freelist head. The index of the next free * chunk is stored in the chunk itself. */ - VALGRIND_MAKE_MEM_DEFINED(SlabChunkGetPointer(chunk), sizeof(int32)); - block->firstFreeChunk = *(int32 *) SlabChunkGetPointer(chunk); + VALGRIND_MAKE_MEM_DEFINED(MemoryChunkGetPointer(chunk), sizeof(int32)); + block->firstFreeChunk = *(int32 *) MemoryChunkGetPointer(chunk); Assert(block->firstFreeChunk >= 0); Assert(block->firstFreeChunk <= slab->chunksPerBlock); @@ -464,47 +409,47 @@ SlabAlloc(MemoryContext context, Size size) slab->minFreeChunks = 0; /* Prepare to initialize the chunk header. */ - VALGRIND_MAKE_MEM_UNDEFINED(chunk, sizeof(SlabChunk)); - - chunk->block = block; - chunk->slab = slab; + VALGRIND_MAKE_MEM_UNDEFINED(chunk, Slab_CHUNKHDRSZ); + MemoryChunkSetHdrMask(chunk, block, MAXALIGN(slab->chunkSize), + MCTX_SLAB_ID); #ifdef MEMORY_CONTEXT_CHECKING /* slab mark to catch clobber of "unused" space */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) { - set_sentinel(SlabChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); VALGRIND_MAKE_MEM_NOACCESS(((char *) chunk) + - sizeof(SlabChunk) + slab->chunkSize, + Slab_CHUNKHDRSZ + slab->chunkSize, slab->fullChunkSize - - (slab->chunkSize + sizeof(SlabChunk))); + (slab->chunkSize + Slab_CHUNKHDRSZ)); } #endif + #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) SlabChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif Assert(slab->nblocks * slab->blockSize == context->mem_allocated); - return SlabChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * SlabFree * Frees allocated memory; memory is removed from the slab. */ -static void -SlabFree(MemoryContext context, void *pointer) +void +SlabFree(void *pointer) { int idx; - SlabContext *slab = castNode(SlabContext, context); - SlabChunk *chunk = SlabPointerGetChunk(pointer); - SlabBlock *block = chunk->block; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) if (!sentinel_ok(pointer, slab->chunkSize)) elog(WARNING, "detected write past chunk end in %s %p", slab->header.name, chunk); @@ -560,13 +505,13 @@ SlabFree(MemoryContext context, void *pointer) { free(block); slab->nblocks--; - context->mem_allocated -= slab->blockSize; + slab->header.mem_allocated -= slab->blockSize; } else dlist_push_head(&slab->freelist[block->nfree], &block->node); Assert(slab->nblocks >= 0); - Assert(slab->nblocks * slab->blockSize == context->mem_allocated); + Assert(slab->nblocks * slab->blockSize == slab->header.mem_allocated); } /* @@ -582,13 +527,14 @@ SlabFree(MemoryContext context, void *pointer) * rather pointless - Slab is meant for chunks of constant size, and moreover * realloc is usually used to enlarge the chunk. */ -static void * -SlabRealloc(MemoryContext context, void *pointer, Size size) +void * +SlabRealloc(void *pointer, Size size) { - SlabContext *slab = castNode(SlabContext, context); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; Assert(slab); - /* can't do actual realloc with slab, but let's try to be gentle */ if (size == slab->chunkSize) return pointer; @@ -597,15 +543,33 @@ SlabRealloc(MemoryContext context, void *pointer, Size size) return NULL; /* keep compiler quiet */ } +/* + * SlabGetChunkContext + * Return the MemoryContext that 'pointer' belongs to. + */ +MemoryContext +SlabGetChunkContext(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; + + Assert(slab != NULL); + + return &slab->header; +} + /* * SlabGetChunkSpace * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -SlabGetChunkSpace(MemoryContext context, void *pointer) +Size +SlabGetChunkSpace(void *pointer) { - SlabContext *slab = castNode(SlabContext, context); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; Assert(slab); @@ -616,7 +580,7 @@ SlabGetChunkSpace(MemoryContext context, void *pointer) * SlabIsEmpty * Is an Slab empty of any allocated space? */ -static bool +bool SlabIsEmpty(MemoryContext context) { SlabContext *slab = castNode(SlabContext, context); @@ -635,7 +599,7 @@ SlabIsEmpty(MemoryContext context) * totals: if not NULL, add stats about this context into *totals. * print_to_stderr: print stats to stderr if true, elog otherwise. */ -static void +void SlabStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, @@ -697,7 +661,7 @@ SlabStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void SlabCheck(MemoryContext context) { int i; @@ -728,6 +692,11 @@ SlabCheck(MemoryContext context) elog(WARNING, "problem in slab %s: number of free chunks %d in block %p does not match freelist %d", name, block->nfree, block, i); + /* make sure the slab pointer correctly points to this context */ + if (block->slab != slab) + elog(WARNING, "problem in slab %s: bogus slab link in block %p", + name, block); + /* reset the bitmap of free chunks for this block */ memset(slab->freechunks, 0, (slab->chunksPerBlock * sizeof(bool))); idx = block->firstFreeChunk; @@ -742,7 +711,7 @@ SlabCheck(MemoryContext context) nfree = 0; while (idx < slab->chunksPerBlock) { - SlabChunk *chunk; + MemoryChunk *chunk; /* count the chunk as free, add it to the bitmap */ nfree++; @@ -750,8 +719,8 @@ SlabCheck(MemoryContext context) /* read index of the next free chunk */ chunk = SlabBlockGetChunk(slab, block, idx); - VALGRIND_MAKE_MEM_DEFINED(SlabChunkGetPointer(chunk), sizeof(int32)); - idx = *(int32 *) SlabChunkGetPointer(chunk); + VALGRIND_MAKE_MEM_DEFINED(MemoryChunkGetPointer(chunk), sizeof(int32)); + idx = *(int32 *) MemoryChunkGetPointer(chunk); } for (j = 0; j < slab->chunksPerBlock; j++) @@ -759,19 +728,19 @@ SlabCheck(MemoryContext context) /* non-zero bit in the bitmap means chunk the chunk is used */ if (!slab->freechunks[j]) { - SlabChunk *chunk = SlabBlockGetChunk(slab, block, j); - - /* chunks have both block and slab pointers, so check both */ - if (chunk->block != block) + MemoryChunk *chunk = SlabBlockGetChunk(slab, block, j); + SlabBlock *chunkblock = (SlabBlock *) MemoryChunkGetBlock(chunk); + + /* + * check the chunk's blockoffset correctly points back to + * the block + */ + if (chunkblock != block) elog(WARNING, "problem in slab %s: bogus block link in block %p, chunk %p", name, block, chunk); - if (chunk->slab != slab) - elog(WARNING, "problem in slab %s: bogus slab link in block %p, chunk %p", - name, block, chunk); - /* there might be sentinel (thanks to alignment) */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) if (!sentinel_ok(chunk, slab->chunkSize)) elog(WARNING, "problem in slab %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); diff --git a/src/include/nodes/memnodes.h b/src/include/nodes/memnodes.h index 16cd56da6d..63d07358cd 100644 --- a/src/include/nodes/memnodes.h +++ b/src/include/nodes/memnodes.h @@ -59,11 +59,12 @@ typedef struct MemoryContextMethods { void *(*alloc) (MemoryContext context, Size size); /* call this free_p in case someone #define's free() */ - void (*free_p) (MemoryContext context, void *pointer); - void *(*realloc) (MemoryContext context, void *pointer, Size size); + void (*free_p) (void *pointer); + void *(*realloc) (void *pointer, Size size); void (*reset) (MemoryContext context); void (*delete_context) (MemoryContext context); - Size (*get_chunk_space) (MemoryContext context, void *pointer); + MemoryContext (*get_chunk_context) (void *pointer); + Size (*get_chunk_space) (void *pointer); bool (*is_empty) (MemoryContext context); void (*stats) (MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, diff --git a/src/include/utils/memutils.h b/src/include/utils/memutils.h index 495d1af201..244f7bf4ff 100644 --- a/src/include/utils/memutils.h +++ b/src/include/utils/memutils.h @@ -79,6 +79,7 @@ extern void MemoryContextDeleteChildren(MemoryContext context); extern void MemoryContextSetIdentifier(MemoryContext context, const char *id); extern void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent); +extern MemoryContext GetMemoryChunkContext(void *pointer); extern Size GetMemoryChunkSpace(void *pointer); extern MemoryContext MemoryContextGetParent(MemoryContext context); extern bool MemoryContextIsEmpty(MemoryContext context); @@ -98,53 +99,6 @@ extern bool MemoryContextContains(MemoryContext context, void *pointer); #define MemoryContextCopyAndSetIdentifier(cxt, id) \ MemoryContextSetIdentifier(cxt, MemoryContextStrdup(cxt, id)) -/* - * GetMemoryChunkContext - * Given a currently-allocated chunk, determine the context - * it belongs to. - * - * All chunks allocated by any memory context manager are required to be - * preceded by the corresponding MemoryContext stored, without padding, in the - * preceding sizeof(void*) bytes. A currently-allocated chunk must contain a - * backpointer to its owning context. The backpointer is used by pfree() and - * repalloc() to find the context to call. - */ -#ifndef FRONTEND -static inline MemoryContext -GetMemoryChunkContext(void *pointer) -{ - MemoryContext context; - - /* - * Try to detect bogus pointers handed to us, poorly though we can. - * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an - * allocated chunk. - */ - Assert(pointer != NULL); - Assert(pointer == (void *) MAXALIGN(pointer)); - - /* - * OK, it's probably safe to look at the context. - */ - context = *(MemoryContext *) (((char *) pointer) - sizeof(void *)); - - AssertArg(MemoryContextIsValid(context)); - - return context; -} -#endif - -/* - * This routine handles the context-type-independent part of memory - * context creation. It's intended to be called from context-type- - * specific creation routines, and noplace else. - */ -extern void MemoryContextCreate(MemoryContext node, - NodeTag tag, - const MemoryContextMethods *methods, - MemoryContext parent, - const char *name); - extern void HandleLogMemoryContextInterrupt(void); extern void ProcessLogMemoryContextInterrupt(void); diff --git a/src/include/utils/memutils_internal.h b/src/include/utils/memutils_internal.h new file mode 100644 index 0000000000..e10a559726 --- /dev/null +++ b/src/include/utils/memutils_internal.h @@ -0,0 +1,130 @@ +/*------------------------------------------------------------------------- + * + * memutils_internal.h + * This file contains declarations for memory allocation utility + * functions for internal use. + * + * + * Portions Copyright (c) 2022, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/utils/memutils_internal.h + * + *------------------------------------------------------------------------- + */ + +#ifndef MEMUTILS_INTERNAL_H +#define MEMUTILS_INTERNAL_H + +#include "utils/memutils.h" + +extern void *AllocSetAlloc(MemoryContext context, Size size); +extern void AllocSetFree(void *pointer); +extern void *AllocSetRealloc(void *pointer, Size size); +extern void AllocSetReset(MemoryContext context); +extern void AllocSetDelete(MemoryContext context); +extern MemoryContext AllocSetGetChunkContext(void *pointer); +extern Size AllocSetGetChunkSpace(void *pointer); +extern bool AllocSetIsEmpty(MemoryContext context); +extern void AllocSetStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); + +#ifdef MEMORY_CONTEXT_CHECKING +extern void AllocSetCheck(MemoryContext context); +#endif + + +extern void *GenerationAlloc(MemoryContext context, Size size); +extern void GenerationFree(void *pointer); +extern void *GenerationRealloc(void *pointer, Size size); +extern void GenerationReset(MemoryContext context); +extern void GenerationDelete(MemoryContext context); +extern MemoryContext GenerationGetChunkContext(void *pointer); +extern Size GenerationGetChunkSpace(void *pointer); +extern bool GenerationIsEmpty(MemoryContext context); +extern void GenerationStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); + +#ifdef MEMORY_CONTEXT_CHECKING +extern void GenerationCheck(MemoryContext context); +#endif + + +/* + * These functions implement the MemoryContext API for Slab contexts. + */ +extern void *SlabAlloc(MemoryContext context, Size size); +extern void SlabFree(void *pointer); +extern void *SlabRealloc(void *pointer, Size size); +extern void SlabReset(MemoryContext context); +extern void SlabDelete(MemoryContext context); +extern MemoryContext SlabGetChunkContext(void *pointer); +extern Size SlabGetChunkSpace(void *pointer); +extern bool SlabIsEmpty(MemoryContext context); +extern void SlabStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); +#ifdef MEMORY_CONTEXT_CHECKING +extern void SlabCheck(MemoryContext context); +#endif + +/* + * MemoryContextMethodID + * A unique identifier for each MemoryContext implementation which + * indicates the index into the mcxt_methods[] array. See mcxt.c. + */ +typedef enum MemoryContextMethodID +{ + MCTX_ASET_ID, + MCTX_GENERATION_ID, + MCTX_SLAB_ID, +} MemoryContextMethodID; + +/* + * The number of bits that 8-byte memory chunk headers can use to encode the + * MemoryContextMethodID. + */ +#define MEMORY_CONTEXT_METHODID_BITS 3 +/* + * The maximum possible value of for a MemoryContextMethodID and the bitmask + * for binary ANDing out unrelated bits in the 8-byte chunk header. This must + * be set to the maximum value that can be represented by + * MEMORY_CONTEXT_METHODID_BITS bits. + */ +#define MEMORY_CONTEXT_METHODID_MASK 7 + +/* + * This routine handles the context-type-independent part of memory + * context creation. It's intended to be called from context-type- + * specific creation routines, and noplace else. + */ +extern void MemoryContextCreate(MemoryContext node, + NodeTag tag, + MemoryContextMethodID method_id, + MemoryContext parent, + const char *name); + +static inline MemoryContextMethodID +GetMemoryChunkMethodID(void *pointer) +{ + uint64 header; + + /* + * Try to detect bogus pointers handed to us, poorly though we can. + * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an + * allocated chunk. + */ + Assert(pointer != NULL); + Assert(pointer == (void *) MAXALIGN(pointer)); + + header = *((uint64 *) ((char *) pointer - sizeof(uint64))); + + return header & MEMORY_CONTEXT_METHODID_MASK; +} + +#endif /* MEMUTILS_INTERNAL_H */ diff --git a/src/include/utils/memutils_memorychunk.h b/src/include/utils/memutils_memorychunk.h new file mode 100644 index 0000000000..3897dfd508 --- /dev/null +++ b/src/include/utils/memutils_memorychunk.h @@ -0,0 +1,231 @@ +/*------------------------------------------------------------------------- + * + * memutils_memorychunk.h + * Here we define a struct named MemoryChunk which implementations of + * MemoryContexts may use as a header for chunks of memory they allocate. + * + * A MemoryChunk provides a lightweight header which a MemoryContext can use + * to store a reference back to the block the which the given chunk is + * allocated on and also an additional 30-bits to store another value such as + * the size of the allocated chunk. + * + * Although MemoryChunks are used by each of our MemoryContexts, future + * implementations may choose to implement their own method for storing chunk + * headers. The only requirement is that the header end with an 8-byte value + * which the least significant 3-bits of are set to the MemoryContextMethodID + * of the given context. + * + * By default, a MemoryChunk is 8 bytes in size, however when + * MEMORY_CONTEXT_CHECKING is defined the header becomes 16 bytes in size due + * to the additional requested_size field. The MemoryContext may use this + * field for whatever they wish, but it is intended to be used for additional + * checks which are only done in MEMORY_CONTEXT_CHECKING builds. + * + * The MemoryChunk contains a uint64 field named 'hdrmask'. This field is + * used to encode 4 separate pieces of information. Starting with the least + * significant bits of 'hdrmask', the bit space is reserved as follows: + * + * 1. 3-bits to indicate the MemoryContextMethodID as defined by + * MEMORY_CONTEXT_METHODID_MASK + * 2. 1-bit to denote an "external" chunk (see below) + * 3. 30-bits reserved for the MemoryContext to use for anything it + * requires. Most MemoryContext likely want to store the size of the + * chunk here. + * 4. 30-bits for the number of bytes that must be subtracted from the chunk + * to obtain the address of the block that the chunk is stored on. + * + * In some cases, for example when memory allocations become large, it's + * possible fields 3 and 4 above are not large enough to store the values + * required for the chunk. In this case, the MemoryContext can choose to mark + * the chunk as "external" by calling the MemoryChunkSetExternal() function. + * When this is done, fields 3 and 4 are unavailable for use by the + * MemoryContext and it's up to the MemoryContext itself to devise its own + * method for getting the reference to the block. + * + * Interface: + * + * MemoryChunkSetHdrMask: + * Used to set up a non-external MemoryChunk. + * + * MemoryChunkSetHdrMaskExternal: + * Used to set up an externally managed MemoryChunk. + * + * MemoryChunkIsExternal: + * Determine if the given MemoryChunk is externally managed, i.e. + * MemoryChunkSetHdrMaskExternal() was called on the chunk. + * + * MemoryChunkGetValue: + * For non-external chunks, return the stored 30-bit value as it was set + * in the call to MemoryChunkSetHdrMask(). + * + * MemoryChunkGetBlock: + * For non-external chunks, return a pointer to the block as it was set + * in the call to MemoryChunkSetHdrMask(). + * + * Also exports: + * MEMORYCHUNK_MAX_VALUE + * MEMORYCHUNK_MAX_BLOCKOFFSET + * PointerGetMemoryChunk + * MemoryChunkGetPointer + * + * Portions Copyright (c) 2022, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/utils/memutils_memorychunk.h + * + *------------------------------------------------------------------------- + */ + +#ifndef MEMUTILS_MEMORYCHUNK_H +#define MEMUTILS_MEMORYCHUNK_H + +#include "utils/memutils_internal.h" + + /* + * The maximum allowed value that MemoryContexts can store in the value + * field. Must be 1 less than a power of 2. + */ +#define MEMORYCHUNK_MAX_VALUE 0x3FFFFFFF + +/* + * The maximum distance in bytes that a MemoryChunk can be offset from the + * block that is storing the chunk. Must be 1 less than a power of 2. + */ +#define MEMORYCHUNK_MAX_BLOCKOFFSET 0x3FFFFFFF + +/* define the least significant base-0 bit of each portion of the hdrmask */ +#define MEMORYCHUNK_EXTERNAL_BASEBIT MEMORY_CONTEXT_METHODID_BITS +#define MEMORYCHUNK_VALUE_BASEBIT (MEMORYCHUNK_EXTERNAL_BASEBIT + 1) +#define MEMORYCHUNK_BLOCKOFFSET_BASEBIT (MEMORYCHUNK_VALUE_BASEBIT + 30) + +/* A magic number for storing in the free bits of an external chunk */ +#define MEMORYCHUNK_MAGIC (UINT64CONST(0xB1A8DB858EB6EFBA) >> \ + MEMORYCHUNK_VALUE_BASEBIT << \ + MEMORYCHUNK_VALUE_BASEBIT) + +typedef struct MemoryChunk +{ +#ifdef MEMORY_CONTEXT_CHECKING + Size requested_size; +#endif + + /* bitfield for storing details about the chunk */ + uint64 hdrmask; /* must be last */ +} MemoryChunk; + +/* Get the MemoryChunk from the pointer */ +#define PointerGetMemoryChunk(p) ((MemoryChunk *) ((char *) (p) - sizeof(MemoryChunk))) +/* Get the pointer from the MemoryChunk */ +#define MemoryChunkGetPointer(c) ((void *) ((char *) (c) + sizeof(MemoryChunk))) + +/* private macros for making the inline functions below more simple */ +#define HdrMaskIsExternal(hdrmask) \ + ((hdrmask) & (1 << MEMORYCHUNK_EXTERNAL_BASEBIT)) +#define HdrMaskGetValue(hdrmask) \ + (((hdrmask) >> MEMORYCHUNK_VALUE_BASEBIT) & MEMORYCHUNK_MAX_VALUE) + +/* + * We should have used up all the bits here, so the compiler is likely to + * optimize out the & MEMORYCHUNK_MAX_BLOCKOFFSET. + */ +#define HdrMaskBlockOffset(hdrmask) \ + (((hdrmask) >> MEMORYCHUNK_BLOCKOFFSET_BASEBIT) & MEMORYCHUNK_MAX_BLOCKOFFSET) + +/* For external chunks only, check the magic number matches */ +#define HdrMaskCheckMagic(hdrmask) \ + (MEMORYCHUNK_MAGIC == \ + ((hdrmask) >> MEMORYCHUNK_VALUE_BASEBIT << MEMORYCHUNK_VALUE_BASEBIT)) +/* + * MemoryChunkSetHdrMask + * Store the given 'block', 'chunk_size' and 'methodid' in the given + * MemoryChunk. + * + * The number of bytes between 'block' and 'chunk' must be <= + * MEMORYCHUNK_MAX_BLOCKOFFSET. + * 'value' must be <= MEMORYCHUNK_MAX_VALUE. + */ +static inline void +MemoryChunkSetHdrMask(MemoryChunk *chunk, void *block, + Size value, MemoryContextMethodID methodid) +{ + Size blockoffset = (char *) chunk - (char *) block; + + Assert((char *) chunk > (char *) block); + Assert(blockoffset <= MEMORYCHUNK_MAX_BLOCKOFFSET); + Assert(value <= MEMORYCHUNK_MAX_VALUE); + Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK); + + chunk->hdrmask = (blockoffset << MEMORYCHUNK_BLOCKOFFSET_BASEBIT) | + (value << MEMORYCHUNK_VALUE_BASEBIT) | + methodid; +} + +/* + * MemoryChunkSetHdrMaskExternal + * Set 'chunk' as an externally managed chunk. Here we only record the + * MemoryContextMethodID and set the external chunk bit. + */ +static inline void +MemoryChunkSetHdrMaskExternal(MemoryChunk *chunk, + MemoryContextMethodID methodid) +{ + Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK); + + chunk->hdrmask = MEMORYCHUNK_MAGIC | (1 << MEMORYCHUNK_EXTERNAL_BASEBIT) | + methodid; +} + +/* + * MemoryChunkIsExternal + * Return true if 'chunk' is marked as external. + */ +static inline bool +MemoryChunkIsExternal(MemoryChunk *chunk) +{ + /* + * External chunks should always store MEMORYCHUNK_MAGIC in the upper + * portion of the hdrmask. + */ + Assert(!HdrMaskIsExternal(chunk->hdrmask) || + HdrMaskCheckMagic(chunk->hdrmask)); + + return HdrMaskIsExternal(chunk->hdrmask); +} + +/* + * MemoryChunkGetValue + * For non-external chunks, returns the value field as it was set in + * MemoryChunkSetHdrMask. + */ +static inline Size +MemoryChunkGetValue(MemoryChunk *chunk) +{ + Assert(!HdrMaskIsExternal(chunk->hdrmask)); + + return HdrMaskGetValue(chunk->hdrmask); +} + +/* + * MemoryChunkGetBlock + * For non-external chunks, returns the pointer to the block as was set + * in MemoryChunkSetHdrMask. + */ +static inline void * +MemoryChunkGetBlock(MemoryChunk *chunk) +{ + Assert(!HdrMaskIsExternal(chunk->hdrmask)); + + return (void *) ((char *) chunk - HdrMaskBlockOffset(chunk->hdrmask)); +} + +/* cleanup all internal definitions */ +#undef MEMORYCHUNK_EXTERNAL_BASEBIT +#undef MEMORYCHUNK_VALUE_BASEBIT +#undef MEMORYCHUNK_BLOCKOFFSET_BASEBIT +#undef MEMORYCHUNK_MAGIC +#undef HdrMaskIsExternal +#undef HdrMaskGetValue +#undef HdrMaskBlockOffset +#undef HdrMaskCheckMagic + +#endif /* MEMUTILS_MEMORYCHUNK_H */ diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 35c9f1efce..86057fd1ba 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -57,6 +57,7 @@ AlenState Alias AllocBlock AllocChunk +AllocFreelistLink AllocPointer AllocSet AllocSetContext @@ -1521,12 +1522,14 @@ MemoizeKey MemoizePath MemoizeState MemoizeTuple +MemoryChunk MemoryContext MemoryContextCallback MemoryContextCallbackFunction MemoryContextCounters MemoryContextData MemoryContextMethods +MemoryContextMethodID MemoryStatsPrintFunc MergeAction MergeActionState -- 2.34.1
pg_allocate_memory_test.patch.txt (text/plain, 5.0K) download diff --git a/src/backend/utils/adt/mcxtfuncs.c b/src/backend/utils/adt/mcxtfuncs.c index bb7cc94024..bdc5a387fc 100644 --- a/src/backend/utils/adt/mcxtfuncs.c +++ b/src/backend/utils/adt/mcxtfuncs.c @@ -193,3 +193,132 @@ pg_log_backend_memory_contexts(PG_FUNCTION_ARGS) PG_RETURN_BOOL(true); } + +typedef struct AllocateTestNext +{ + struct AllocateTestNext *next; /* ptr to the next allocation */ +} AllocateTestNext; + +/* #define ALLOCATE_TEST_DEBUG */ +/* + * pg_allocate_memory_test + * Used to test the performance of a memory context types + */ +Datum +pg_allocate_memory_test(PG_FUNCTION_ARGS) +{ + int32 chunk_size = PG_GETARG_INT32(0); + int64 keep_memory = PG_GETARG_INT64(1); + int64 total_alloc = PG_GETARG_INT64(2); + char *context_type = PG_GETARG_CSTRING(3); + int64 curr_memory_use = 0; + int64 remaining_alloc_bytes = total_alloc; + MemoryContext context; + MemoryContext oldContext; + AllocateTestNext *next_free_ptr = NULL; + AllocateTestNext *last_alloc = NULL; + + if (chunk_size < sizeof(AllocateTestNext)) + elog(ERROR, "chunk_size (%d) must be at least %ld bytes", chunk_size, + sizeof(AllocateTestNext)); + if (keep_memory > total_alloc) + elog(ERROR, "keep_memory (" INT64_FORMAT ") must be less than total_alloc (" INT64_FORMAT ")", + keep_memory, total_alloc); + + if (strcmp(context_type, "generation") == 0) + context = GenerationContextCreate(CurrentMemoryContext, + "pg_allocate_memory_test", + ALLOCSET_DEFAULT_SIZES); + else if (strcmp(context_type, "aset") == 0) + context = AllocSetContextCreate(CurrentMemoryContext, + "pg_allocate_memory_test", + ALLOCSET_DEFAULT_SIZES); + else if (strcmp(context_type, "slab") == 0) + context = SlabContextCreate(CurrentMemoryContext, + "pg_allocate_memory_test", + ALLOCSET_DEFAULT_MAXSIZE, + chunk_size); + else + elog(ERROR, "context_type must be \"generation\", \"aset\" or \"slab\""); + + oldContext = MemoryContextSwitchTo(context); + + while (remaining_alloc_bytes > 0) + { + AllocateTestNext *curr_alloc; + + CHECK_FOR_INTERRUPTS(); + + /* Allocate the memory and update the counters */ + curr_alloc = (AllocateTestNext *) palloc(chunk_size); + remaining_alloc_bytes -= chunk_size; + curr_memory_use += chunk_size; + +#ifdef ALLOCATE_TEST_DEBUG + elog(NOTICE, "alloc %p (curr_memory_use " INT64_FORMAT " bytes, remaining_alloc_bytes " INT64_FORMAT ")", curr_alloc, curr_memory_use, remaining_alloc_bytes); +#endif + + /* + * Point the last allocate to this one so that we can free allocations + * starting with the oldest first. + */ + curr_alloc->next = NULL; + if (last_alloc != NULL) + last_alloc->next = curr_alloc; + + if (next_free_ptr == NULL) + { + /* + * Remember the first chunk to free. We will follow the ->next + * pointers to find the next chunk to free when freeing memory + */ + next_free_ptr = curr_alloc; + } + + /* + * If the currently allocated memory has reached or exceeded the amount + * of memory we want to keep allocated at once then we'd better free + * some. Since all allocations are the same size we only need to free + * one allocation per loop. + */ + if (curr_memory_use >= keep_memory) + { + AllocateTestNext *next = next_free_ptr->next; + + /* free the memory and update the current memory usage */ + pfree(next_free_ptr); + curr_memory_use -= chunk_size; + +#ifdef ALLOCATE_TEST_DEBUG + elog(NOTICE, "free %p (curr_memory_use " INT64_FORMAT " bytes, remaining_alloc_bytes " INT64_FORMAT ")", next_free_ptr, curr_memory_use, remaining_alloc_bytes); +#endif + /* get the next chunk to free */ + next_free_ptr = next; + } + + if (curr_memory_use > 0) + last_alloc = curr_alloc; + else + last_alloc = NULL; + } + + /* cleanup loop -- pfree remaining memory */ + while (next_free_ptr != NULL) + { + AllocateTestNext *next = next_free_ptr->next; + + /* free the memory and update the current memory usage */ + pfree(next_free_ptr); + curr_memory_use -= chunk_size; + +#ifdef ALLOCATE_TEST_DEBUG + elog(NOTICE, "free %p (curr_memory_use " INT64_FORMAT " bytes, remaining_alloc_bytes " INT64_FORMAT ")", next_free_ptr, curr_memory_use, remaining_alloc_bytes); +#endif + + next_free_ptr = next; + } + + MemoryContextSwitchTo(oldContext); + + PG_RETURN_VOID(); +} diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index be47583122..38dd030c8e 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -8101,6 +8101,12 @@ prorettype => 'bool', proargtypes => 'int4', prosrc => 'pg_log_backend_memory_contexts' }, +# just for testing memory context allocation speed +{ oid => '9319', descr => 'for testing performance of allocation and freeing', + proname => 'pg_allocate_memory_test', provolatile => 'v', + prorettype => 'void', proargtypes => 'int4 int8 int8 cstring', + prosrc => 'pg_allocate_memory_test' }, + # non-persistent series generator { oid => '1066', descr => 'non-persistent series generator', proname => 'generate_series', prorows => '1000',
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-23 09:03  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-08-23 09:03 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Thu, 18 Aug 2022 at 01:58, David Rowley <dgrowleyml@gmail.com> wrote:
> Does anyone else want to have a go at taking v4 for a spin to see how
> it performs?

I've been working on this patch again.  The v4 patch didn't quite get
the palloc(0) behaviour correct. There were no actual bugs in
non-MEMORY_CONTEXT_CHECKING builds. It was just my detection method
for free'd chunks in AllocSetCheck and GenerationCheck that was
broken.  In the free function, I'd been setting the requested_size
back to 0 to indicate a free'd chunk.  Unfortunately that was getting
confused with palloc(0) chunks during the checks.  The solution to
that was to add:

#define InvalidAllocSize SIZE_MAX

to memutils.h and set free'd chunk's requested_size to that value.
That seems fine, because:

#define MaxAllocHugeSize (SIZE_MAX / 2)

After fixing that I moved on and did some quite extensive benchmarking
of the patch.  I've learned quite a few things from this, namely:

a) putting the freelist pointer at the end of the chunk costs us in performance.
b) the patch makes GenerationFree() slower than it is in master.

I believe a) is due to the chunk header and the freelist pointer being
on different cache lines when the chunk becomes larger.  This means
having to load more cache lines resulting in slower performance.
For b), I'm not sure the reason for this. I wondered if it is due to
how the pointer to the MemoryContext is obtained in GenerationFree().
We first look at the MemoryChunk to find the block offset, then get
the address of the block from that, we then must dereference the
block->context pointer to get the owning MemoryContext.  Previously we
just looked at the GenerationChunk's context field.

Due to a), I decided to benchmark the patch twice, once with the
freelist pointer at the end of the chunk (as it was in v4 patch), and
again with the pointer at the start of the chunk.
For b), I looked again at GenerationFree() and saw that I really only
need to look at the owning context when the block is to be freed.  The
vast majority of calls won't need to do that.  Unfortunately moving
the "set = block->context;" to just after we've checked if the block
needs to be freed did not improve things. I've not run the complete
benchmark again to make sure though, only a single data point of it.

Benchmarking:

I did this benchmarking on an AMD 3990x machine which has 64GB of RAM
installed.  The tests I performed entirely used two SQL functions that
I've written especially for exercising palloc() and pfree().

To allow me to run the tests I wanted to, I wrote the following functions:

1. pg_allocate_memory_test(): Accepts an allocation size parameter
(chunk_size), an amount of memory to keep palloc'd at once. Once this
amount is reached we'll start pfreeing 1 chunk for every newly
allocated chunk. Another parameter controls the total amount of
allocations. We'll do this number / chunk_size allocations in total.
The final parameter specifies the memory context type to use; aset,
generation, etc.  The intention of this function is to see if
palloc/pfree has become faster or slower and also see how the
reduction in the chunk header size affects performance when the amount
of memory being allocated at once starts to get big. I'm expecting
better CPU cache hit ratios due to the memory reductions.

2. pg_allocate_memory_test_reset().  Since we mostly don't do pfree(),
function #1 might not be that accurate a test.  Mostly we palloc()
then MemoryContextReset().

Tests:

I ran both of the above functions starting with a chunk size of 8 and
doubled that each time up to 1024.  I tested both aset.c and
generation.c context types.

In order to check how performance is affected by allocating more
memory at once, I started the total concurrent memory allocation at 1k
and doubled each time to 1GB. 3 branches tested; master, patch (with
freelist at end of chunk) and patch (with freelist at start of chunk).

So, 2 memory context types, 8 chunk sizes, 21 concurrent allocation
sizes, 2 functions, 3 * 2 * 8 * 21 * 2 = 2016 data points.

I ran each test for 30 seconds in pgbench. I used 20GBs as the total
amount of memory to allocate.

The results:

The patch with freelist pointers at the start of the chunk seems a
clear winner in the pg_allocate_memory_test_reset() test for both aset
(graph1.gif) and generation (graph2.gif). There are a few data points
where the times come out slower than master, but not by much. I
suspect this might be noise, but didn't investigate.

For function #1, pg_allocate_memory_test(), the performance is pretty
complex.  For aset, the performance is mostly better with the freelist
start version of the patch. There is an exception to this with the 8
byte chunk size where performance comes out worse than master. That
flips around with the 16 byte chunk test and becomes better overall.
Ignoring the 8 byte chunk, the remaining performance is faster than
master.  This shows that having the freelist pointer at the start of
the free'd chunk is best (graph3.gif) (graph4.gif better shows this
for the larger chunks).

With the generation context, it's complex.  The more memory we
allocate at once, the better performance generally gets (especially
for larger chunks).  I wondered if this might be due to the reduction
in the chunk header size, but I'm really not sure as I'd have expected
the most gains to appear in small chunks if that was the case as the
header is a larger proportion of the total allocation size for those.
Weirdly the opposite is true, larger chunks are showing better gains
in the patched version when compared to the same data point in the
unpatched master branch. graph5.gif shows this for the smaller chunks
and graph6.gif for the larger ones

In summary, I'm not too concerned that GenerationFree() is a small
amount slower.  I think the other gains are significant enough to make
up for this.  We could probably modify dumptuples() so that WRITETUP()
does not call pfree() just before we do
MemoryContextReset(state->base.tuplecontext). Those pfree calls are a
complete waste of effort, although we *can't* unconditionally remove
that pfree() call in WRITETUP().

I've attached the full results in bench_results.sql.  If anyone else
wants to repeat these tests then I've attached
pg_allocate_memory_test.sh.txt and
allocate_performance_functions.patch.txt with the 2 new SQL functions
I used to test with.

Finally, the v5 patch with the fixes mentioned above.

Also, I'm leaning towards wanting to put the freelist pointer at the
start of the chunk's memory rather than at the end.  I understand that
code which actually does something with the allocated memory is more
likely to have loaded the useful cache lines already and that's not
something my benchmark would have done, but for larger chunks the
power of 2 wastage is likely to mean that many of those cache lines
nearing the end of the chunk would never have to be loaded at all.

I'm pretty keen to get this patch committed early next week.  This is
quite core infrastructure, so it would be good if the patch gets a few
extra eyeballs on it before then.

David

Attachments:

pg_allocate_memory_test.sh.txt (text/plain, 1.1K) download #!/bin/bash dbname=postgres sec=30 for branch in 'pg_allocate_memory_test' 'pg_allocate_memory_test_plus_v5' 'pg_allocate_memory_test_plus_v5_start' do cd ~/pg_src git checkout $branch make clean -s make -j -s make install -s cd ~ pg_ctl stop -D pgdata pg_ctl start -D pgdata -l pg.log sleep 2 for context in 'aset' 'generation' do for chunk in 8 16 32 64 128 256 512 1024 do for alloc_size in 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728 268435456 536870912 1073741824 do echo "select pg_allocate_memory_test($chunk, $alloc_size, 20::bigint*1024*1024*1024, '$context');" > bench.sql echo "Testing pg_allocate_memory_test $branch $context $chunk $alloc_size" pgbench -n -f bench.sql -T $sec $dbname echo "select pg_allocate_memory_test_reset($chunk, $alloc_size, 20::bigint*1024*1024*1024, '$context');" > bench.sql echo "Testing pg_allocate_memory_test_reset $branch $context $chunk $alloc_size" pgbench -n -f bench.sql -T $sec $dbname done done done done
graph1.gif (image/gif, 93.0K) download view image
graph2.gif (image/gif, 97.7K) download view image
graph3.gif (image/gif, 73.8K) download view image
graph4.gif (image/gif, 84.2K) download view image
graph6.gif (image/gif, 83.8K) download view image
graph5.gif (image/gif, 74.1K) download view image
bench_results.sql (application/octet-stream, 140.6K) download
allocate_performance_functions.patch.txt (text/plain, 7.4K) download diff --git a/src/backend/utils/adt/mcxtfuncs.c b/src/backend/utils/adt/mcxtfuncs.c index bb7cc94024..6a0c1b53dc 100644 --- a/src/backend/utils/adt/mcxtfuncs.c +++ b/src/backend/utils/adt/mcxtfuncs.c @@ -193,3 +193,199 @@ pg_log_backend_memory_contexts(PG_FUNCTION_ARGS) PG_RETURN_BOOL(true); } + +typedef struct AllocateTestNext +{ + struct AllocateTestNext *next; /* ptr to the next allocation */ +} AllocateTestNext; + +/* #define ALLOCATE_TEST_DEBUG */ +/* + * pg_allocate_memory_test + * Used to test the performance of a memory context types + */ +Datum +pg_allocate_memory_test(PG_FUNCTION_ARGS) +{ + int32 chunk_size = PG_GETARG_INT32(0); + int64 keep_memory = PG_GETARG_INT64(1); + int64 total_alloc = PG_GETARG_INT64(2); + char *context_type = PG_GETARG_CSTRING(3); + int64 curr_memory_use = 0; + int64 remaining_alloc_bytes = total_alloc; + MemoryContext context; + MemoryContext oldContext; + AllocateTestNext *next_free_ptr = NULL; + AllocateTestNext *last_alloc = NULL; + + if (chunk_size < sizeof(AllocateTestNext)) + elog(ERROR, "chunk_size (%d) must be at least %ld bytes", chunk_size, + sizeof(AllocateTestNext)); + if (keep_memory > total_alloc) + elog(ERROR, "keep_memory (" INT64_FORMAT ") must be less than total_alloc (" INT64_FORMAT ")", + keep_memory, total_alloc); + + if (strcmp(context_type, "generation") == 0) + context = GenerationContextCreate(CurrentMemoryContext, + "pg_allocate_memory_test", + ALLOCSET_DEFAULT_SIZES); + else if (strcmp(context_type, "aset") == 0) + context = AllocSetContextCreate(CurrentMemoryContext, + "pg_allocate_memory_test", + ALLOCSET_DEFAULT_SIZES); + else if (strcmp(context_type, "slab") == 0) + context = SlabContextCreate(CurrentMemoryContext, + "pg_allocate_memory_test", + ALLOCSET_DEFAULT_MAXSIZE, + chunk_size); + else + elog(ERROR, "context_type must be \"generation\", \"aset\" or \"slab\""); + + oldContext = MemoryContextSwitchTo(context); + + while (remaining_alloc_bytes > 0) + { + AllocateTestNext *curr_alloc; + + CHECK_FOR_INTERRUPTS(); + + /* Allocate the memory and update the counters */ + curr_alloc = (AllocateTestNext *) palloc(chunk_size); + remaining_alloc_bytes -= chunk_size; + curr_memory_use += chunk_size; + +#ifdef ALLOCATE_TEST_DEBUG + elog(NOTICE, "alloc %p (curr_memory_use " INT64_FORMAT " bytes, remaining_alloc_bytes " INT64_FORMAT ")", curr_alloc, curr_memory_use, remaining_alloc_bytes); +#endif + + /* + * Point the last allocate to this one so that we can free allocations + * starting with the oldest first. + */ + curr_alloc->next = NULL; + if (last_alloc != NULL) + last_alloc->next = curr_alloc; + + if (next_free_ptr == NULL) + { + /* + * Remember the first chunk to free. We will follow the ->next + * pointers to find the next chunk to free when freeing memory + */ + next_free_ptr = curr_alloc; + } + + /* + * If the currently allocated memory has reached or exceeded the amount + * of memory we want to keep allocated at once then we'd better free + * some. Since all allocations are the same size we only need to free + * one allocation per loop. + */ + if (curr_memory_use >= keep_memory) + { + AllocateTestNext *next = next_free_ptr->next; + + /* free the memory and update the current memory usage */ + pfree(next_free_ptr); + curr_memory_use -= chunk_size; + +#ifdef ALLOCATE_TEST_DEBUG + elog(NOTICE, "free %p (curr_memory_use " INT64_FORMAT " bytes, remaining_alloc_bytes " INT64_FORMAT ")", next_free_ptr, curr_memory_use, remaining_alloc_bytes); +#endif + /* get the next chunk to free */ + next_free_ptr = next; + } + + if (curr_memory_use > 0) + last_alloc = curr_alloc; + else + last_alloc = NULL; + } + + /* cleanup loop -- pfree remaining memory */ + while (next_free_ptr != NULL) + { + AllocateTestNext *next = next_free_ptr->next; + + /* free the memory and update the current memory usage */ + pfree(next_free_ptr); + curr_memory_use -= chunk_size; + +#ifdef ALLOCATE_TEST_DEBUG + elog(NOTICE, "free %p (curr_memory_use " INT64_FORMAT " bytes, remaining_alloc_bytes " INT64_FORMAT ")", next_free_ptr, curr_memory_use, remaining_alloc_bytes); +#endif + + next_free_ptr = next; + } + + MemoryContextSwitchTo(oldContext); + + PG_RETURN_VOID(); +} + +Datum +pg_allocate_memory_test_reset(PG_FUNCTION_ARGS) +{ + int32 chunk_size = PG_GETARG_INT32(0); + int64 keep_memory = PG_GETARG_INT64(1); + int64 total_alloc = PG_GETARG_INT64(2); + char *context_type = PG_GETARG_CSTRING(3); + int64 curr_memory_use = 0; + int64 remaining_alloc_bytes = total_alloc; + MemoryContext context; + MemoryContext oldContext; + void *curr_alloc; + + if (chunk_size < 1) + elog(ERROR, "size of chunk must be above 0"); + if (keep_memory > total_alloc) + elog(ERROR, "keep_memory (" INT64_FORMAT ") must be less than total_alloc (" INT64_FORMAT ")", + keep_memory, total_alloc); + + if (strcmp(context_type, "generation") == 0) + context = GenerationContextCreate(CurrentMemoryContext, + "pg_allocate_memory_test", + ALLOCSET_DEFAULT_SIZES); + else if (strcmp(context_type, "aset") == 0) + context = AllocSetContextCreate(CurrentMemoryContext, + "pg_allocate_memory_test", + ALLOCSET_DEFAULT_SIZES); + else if (strcmp(context_type, "slab") == 0) + context = SlabContextCreate(CurrentMemoryContext, + "pg_allocate_memory_test", + ALLOCSET_DEFAULT_MAXSIZE, + chunk_size); + else + elog(ERROR, "context_type must be \"generation\", \"aset\" or \"slab\""); + + oldContext = MemoryContextSwitchTo(context); + + while (remaining_alloc_bytes > 0) + { + CHECK_FOR_INTERRUPTS(); + + /* Allocate the memory and update the counters */ + curr_alloc = palloc(chunk_size); + remaining_alloc_bytes -= chunk_size; + curr_memory_use += chunk_size; + +#ifdef ALLOCATE_TEST_DEBUG + elog(NOTICE, "alloc %p (curr_memory_use " INT64_FORMAT " bytes, remaining_alloc_bytes " INT64_FORMAT ")", curr_alloc, curr_memory_use, remaining_alloc_bytes); +#endif + + /* + * If the currently allocated memory has reached or exceeded the amount + * of memory we want to keep allocated at once then reset the context. + */ + if (curr_memory_use >= keep_memory) + { + curr_memory_use = 0; + MemoryContextReset(context); + } + } + + MemoryContextSwitchTo(oldContext); + MemoryContextDelete(context); + + PG_RETURN_VOID(); +} diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index be47583122..c3a7383a6d 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -8101,6 +8101,18 @@ prorettype => 'bool', proargtypes => 'int4', prosrc => 'pg_log_backend_memory_contexts' }, +# just for testing memory context allocation speed +{ oid => '9319', descr => 'for testing performance of allocation and freeing', + proname => 'pg_allocate_memory_test', provolatile => 'v', + prorettype => 'void', proargtypes => 'int4 int8 int8 cstring', + prosrc => 'pg_allocate_memory_test' }, + +# just for testing memory context allocation speed +{ oid => '9320', descr => 'for testing performance of allocation and resetting', + proname => 'pg_allocate_memory_test_reset', provolatile => 'v', + prorettype => 'void', proargtypes => 'int4 int8 int8 cstring', + prosrc => 'pg_allocate_memory_test_reset' }, + # non-persistent series generator { oid => '1066', descr => 'non-persistent series generator', proname => 'generate_series', prorows => '1000',
v5-0001-Improve-performance-of-and-reduce-overheads-of-me.patch (text/plain, 104.3K) download From 78745e80ed7910eb3aef2cfc8419239b23bdb71f Mon Sep 17 00:00:00 2001 From: David Rowley <dgrowley@gmail.com> Date: Thu, 9 Jun 2022 20:09:22 +1200 Subject: [PATCH v5] Improve performance of and reduce overheads of memory management Whenever we palloc a chunk of memory, traditionally, we prefix the returned pointer with a pointer to the memory context to which the chunk belongs. This is required so that we're able to easily determine the owning context when performing operations such as pfree() and repalloc(). For the AllocSet context, prior to this commit we additionally prefixed the pointer to the owning context with the size of the chunk. This made the header 16 bytes in size. This 16-byte overhead was required for all AllocSet allocations regardless of the allocation size. For the generation context, the problem was worse; in addition to the pointer to the owning context and chunk size, we also stored a pointer to the owning block so that we could track the number of freed chunks on a block. The slab allocator had a 16-byte chunk header. The changes being made here reduce the chunk header size down to just 8 bytes for all 3 of our memory context types. For small to medium sized allocations, this significantly increases the number of chunks that we can fit on a given block which results in much more efficient use of memory. Additionally, this commit completely changes the rule that pointers to palloc'd memory must be directly prefixed by a pointer to the owning memory context and instead, we now insist that they're directly prefixed by an 8-byte value where the least significant 3-bits are set to a value to indicate which type of memory context the pointer belongs to. Using those 3 bits as an index (known as MemoryContextMethodID) to a new array which stores the methods for each memory context type, we're now able to pass the pointer given to functions such as pfree() and repalloc() to the function specific to that context implementation to allow them to devise their own methods of finding the memory context which owns the given allocated chunk of memory. The reason we're able to reduce the chunk header down to just 8 bytes is because of the way we make use of the remaining 61 bits of the required 8-byte chunk header. Here we also implement a general-purpose MemoryChunk struct which makes use of those 61 remaining bits to allow the storage of a 30-bit value which the MemoryContext is free to use as it pleases, and also the number of bytes which must be subtracted from the chunk to get a reference to the block that the chunk is stored on (also 30 bits). The 1 additional remaining bit is to denote if the chunk is an "external" chunk or not. External here means that the chunk header does not store the 30-bit value or the block offset. The MemoryContext can use these external chunks at any time, but must use them if any of the two 30-bit fields are not large enough for the value(s) that need to be stored in them. When the chunk is marked as external, it is up to the MemoryContext to devise its own means to determine the block offset. Using 3-bits for the MemoryContextMethodID does mean we're limiting ourselves to only having a maximum of 8 different memory context types. We could reduce the bit space for the 30-bit value a little to make way for more than 3 bits, but it seems like it might be better to do that only if we ever need more than 8 context types. This would only be a problem if some future memory context type which does not use MemoryChunk really couldn't give up any of the 61 remaining bits in the chunk header. With this MemoryChunk, each of our 3 memory context types can quickly obtain a reference to the block any given chunk is located on. AllocSet is able to find the context to which the chunk is owned by first obtaining a reference to the block by subtracting the block offset as is stored in the 'hdrmask' field and then referencing the block's 'aset' field. The Generation context uses the same method, but GenerationBlock did not have a field pointing back to the owning context, so one is added by this commit. In aset.c and generation.c, all allocations larger than allocChunkLimit are stored on dedicated blocks. When there's just a single chunk on a block like this, it's easy to find the block from the chunk, we just subtract the size of the block header from the chunk pointer. The size of these chunks is also known as we store the endptr on the block, so we can just subtract the pointer to the allocated memory from that. Because we can easily find the owning block and the size of the chunk for these dedicated blocks, we just always use external chunks for allocation sizes larger than allocChunkLimit. For geneartion.c, this sidesteps the problem of non-external MemoryChunks being unable to represent chunk sizes >= 1GB. This is less of a problem for aset.c as we store the freelist index in the MemoryChunk's spare 30-bit field. we can easily reverse engineer the chunk size from this when needed. Storing this saves AllocSetFree() from having to make a call to AllocSetFreeIndex() to determine which freelist to put the newly freed chunk on. For the slab allocator, this commit adds a new restriction that slab chunks cannot be >= 1GB in size. If there happened to be any users of slab.c which used chunk sizes this large, they really should be using AllocSet instead. Here we also add a restriction that normal non-dedicated blocks cannot be 1GB or larger. It's now not possible to pass a 'maxBlockSize' >= 1GB during the creation of an AllocSet or Generation context. Allocations can still be larger than 1GB, it's just these will always be on dedicated blocks (which are not restricted to 1GB in size). Author: Andres Freund, David Rowley Discussion: https://postgr.es/m/CAApHDvpjauCRXcgcaL6+e3eqecEHoeRm9D-kcbuvBitgPnW=vw@mail.gmail.com --- src/backend/utils/mmgr/README | 60 ++- src/backend/utils/mmgr/aset.c | 506 ++++++++++++----------- src/backend/utils/mmgr/generation.c | 350 ++++++++-------- src/backend/utils/mmgr/mcxt.c | 91 +++- src/backend/utils/mmgr/slab.c | 197 ++++----- src/include/nodes/memnodes.h | 7 +- src/include/utils/memutils.h | 51 +-- src/include/utils/memutils_internal.h | 130 ++++++ src/include/utils/memutils_memorychunk.h | 231 +++++++++++ src/tools/pgindent/typedefs.list | 3 + 10 files changed, 1032 insertions(+), 594 deletions(-) create mode 100644 src/include/utils/memutils_internal.h create mode 100644 src/include/utils/memutils_memorychunk.h diff --git a/src/backend/utils/mmgr/README b/src/backend/utils/mmgr/README index 221b4bd343..c94194f7d3 100644 --- a/src/backend/utils/mmgr/README +++ b/src/backend/utils/mmgr/README @@ -378,35 +378,55 @@ MemoryContext like the parent and child contexts, and the name of the context. This is essentially an abstract superclass, and the behavior is -determined by the "methods" pointer is its virtual function table -(struct MemoryContextMethods). Specific memory context types will use -derived structs having these fields as their first fields. All the +determined by the "methods" pointer which references which set of +MemoryContextMethods are to be used. Specific memory context types will +use derived structs having these fields as their first fields. All the contexts of a specific type will have methods pointers that point to -the same static table of function pointers. +the corresponding element in the mcxt_methods[] array as defined in mcxt.c. While operations like allocating from and resetting a context take the relevant MemoryContext as a parameter, operations like free and realloc are trickier. To make those work, we require all memory context types to produce allocated chunks that are immediately, -without any padding, preceded by a pointer to the corresponding -MemoryContext. +without any padding, preceded by a uint64 value of which the least +significant 3 bits are set to the owning context's MemoryContextMethodID. +This allows the code to determine the correct MemoryContextMethods to +use by looking up the mcxt_methods[] array using the 3 bits as an index +into that array. If a type of allocator needs additional information about its chunks, like e.g. the size of the allocation, that information can in turn -precede the MemoryContext. This means the only overhead implied by -the memory context mechanism is a pointer to its context, so we're not -constraining context-type designers very much. - -Given this, routines like pfree determine their corresponding context -with an operation like (although that is usually encapsulated in -GetMemoryChunkContext()) - - MemoryContext context = *(MemoryContext*) (((char *) pointer) - sizeof(void *)); - -and then invoke the corresponding method for the context - - context->methods->free_p(pointer); - +either be encoded into the remaining 61 bits of the preceding uint64 value +or if more space is required, additional values may be stored directly prior +to the uint64 value. It is up to the context implementation to manage this. + +Given this, routines like pfree can determine which set of +MemoryContextMethods to call the free_p function for by calling +GetMemoryChunkMethodID() and finding the corresponding MemoryContextMethods +in the mcxt_methods array[]. For convenience, the MCXT_METHOD() macro is +provided, making the code as simple as: + +void +pfree(void *pointer) +{ + MCXT_METHOD(pointer, free_p)(pointer); +} + +All of the current memory contexts make use of the MemoryChunk header type +which is defined in memutils_memorychunk.h. This suits all of the existing +context types well as it makes use of the remaining 61-bits of the uint64 +header to efficiently encode the size of the chunk of memory (or freelist +index, in the case of aset.c) and the number of bytes which must be subtracted +from the chunk in order to obtain a reference to the block that the chunk +belongs to. 30 bits are used for each of these. If more than 30 bits are +required then the memory context must manage that itself. This can be done by +calling the MemoryChunkSetHdrMaskExternal() function on the given chunk. +Currently, each memory context type stores large allocations on dedicated +blocks (which always contain only a single chunk). For these, finding the +block is simple as we know that the chunk must be the first on the given +block, so the block is always at a fixed offset to the chunk. For these, +finding the size of the chunk is also simple as the block always stores an +endptr which we can use to calculate the size of the chunk. More Control Over aset.c Behavior --------------------------------- diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index ec3e264a73..a4b4e2ea45 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -49,6 +49,8 @@ #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" /*-------------------- * Chunk freelist k holds chunks of size 1 << (k + ALLOC_MINBITS), @@ -66,7 +68,9 @@ * CAUTION: ALLOC_MINBITS must be large enough so that * 1<<ALLOC_MINBITS is at least MAXALIGN, * or we may fail to align the smallest chunks adequately. - * 8-byte alignment is enough on all currently known machines. + * 8-byte alignment is enough on all currently known machines. This 8-byte + * minimum also allows us to store a pointer to the next freelist item within + * the chunk of memory itself. * * With the current parameters, request sizes up to 8K are treated as chunks, * larger requests go into dedicated blocks. Change ALLOCSET_NUM_FREELISTS @@ -98,10 +102,9 @@ */ #define ALLOC_BLOCKHDRSZ MAXALIGN(sizeof(AllocBlockData)) -#define ALLOC_CHUNKHDRSZ sizeof(struct AllocChunkData) +#define ALLOC_CHUNKHDRSZ sizeof(MemoryChunk) typedef struct AllocBlockData *AllocBlock; /* forward reference */ -typedef struct AllocChunkData *AllocChunk; /* * AllocPointer @@ -109,6 +112,33 @@ typedef struct AllocChunkData *AllocChunk; */ typedef void *AllocPointer; +/* + * AllocFreelistLink + * When pfreeing memory, if we maintain a freelist for the given chunk's + * size then we use a AllocFreelistLink to point to the current item in + * the AllocSetContext's freelist and then set the given freelist element + * to point to the chunk being freed. + */ +typedef struct AllocFreelistLink +{ + MemoryChunk *next; +} AllocFreelistLink; + +/* + * Obtain a AllocFreelistLink for the given chunk. Allocation sizes are + * always at least sizeof(AllocFreelistLink), so we reuse the pointer's memory + * itself to store the freelist link. To make it less likely that any write + * after pfree() bugs corrupt this, we put the link at the very end of the + * allocated chunk. + */ +#define GetFreeListLink(chkptr, chksz) \ + (AllocFreelistLink *) ((char *) (chkptr) + ALLOC_CHUNKHDRSZ + \ + (chksz) - sizeof(AllocFreelistLink)) + +/* Determine the size of the chunk based on the freelist index */ +#define GetChunkSizeFromFreelistIdx(fidx) \ + ((((Size) 1) << ALLOC_MINBITS) << (fidx)) + /* * AllocSetContext is our standard implementation of MemoryContext. * @@ -123,7 +153,7 @@ typedef struct AllocSetContext MemoryContextData header; /* Standard memory-context fields */ /* Info about storage allocated in this context: */ AllocBlock blocks; /* head of list of blocks in this set */ - AllocChunk freelist[ALLOCSET_NUM_FREELISTS]; /* free chunk lists */ + MemoryChunk *freelist[ALLOCSET_NUM_FREELISTS]; /* free chunk lists */ /* Allocation parameters for this context: */ Size initBlockSize; /* initial block size */ Size maxBlockSize; /* maximum block size */ @@ -139,8 +169,8 @@ typedef AllocSetContext *AllocSet; /* * AllocBlock * An AllocBlock is the unit of memory that is obtained by aset.c - * from malloc(). It contains one or more AllocChunks, which are - * the units requested by palloc() and freed by pfree(). AllocChunks + * from malloc(). It contains one or more MemoryChunks, which are + * the units requested by palloc() and freed by pfree(). MemoryChunks * cannot be returned to malloc() individually, instead they are put * on freelists by pfree() and re-used by the next palloc() that has * a matching request size. @@ -158,48 +188,12 @@ typedef struct AllocBlockData } AllocBlockData; /* - * AllocChunk - * The prefix of each piece of memory in an AllocBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "aset" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). We simplify matters for this - * module by requiring sizeof(AllocChunkData) to be maxaligned, and then - * we can ensure things work by adding any required alignment padding before - * the "aset" field. There is a static assertion below that the alignment - * is done correctly. - */ -typedef struct AllocChunkData -{ - /* size is always the size of the usable space in the chunk */ - Size size; -#ifdef MEMORY_CONTEXT_CHECKING - /* when debugging memory usage, also store actual requested size */ - /* this is zero in a free chunk */ - Size requested_size; - -#define ALLOCCHUNK_RAWSIZE (SIZEOF_SIZE_T * 2 + SIZEOF_VOID_P) -#else -#define ALLOCCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P) -#endif /* MEMORY_CONTEXT_CHECKING */ - - /* ensure proper alignment by adding padding if needed */ -#if (ALLOCCHUNK_RAWSIZE % MAXIMUM_ALIGNOF) != 0 - char padding[MAXIMUM_ALIGNOF - ALLOCCHUNK_RAWSIZE % MAXIMUM_ALIGNOF]; -#endif - - /* aset is the owning aset if allocated, or the freelist link if free */ - void *aset; - /* there must not be any padding to reach a MAXALIGN boundary here! */ -} AllocChunkData; - -/* - * Only the "aset" field should be accessed outside this module. + * Only the "hdrmask" field should be accessed outside this module. * We keep the rest of an allocated chunk's header marked NOACCESS when using * valgrind. But note that chunk headers that are in a freelist are kept * accessible, for simplicity. */ -#define ALLOCCHUNK_PRIVATE_LEN offsetof(AllocChunkData, aset) +#define ALLOCCHUNK_PRIVATE_LEN offsetof(MemoryChunk, hdrmask) /* * AllocPointerIsValid @@ -213,10 +207,12 @@ typedef struct AllocChunkData */ #define AllocSetIsValid(set) PointerIsValid(set) -#define AllocPointerGetChunk(ptr) \ - ((AllocChunk)(((char *)(ptr)) - ALLOC_CHUNKHDRSZ)) -#define AllocChunkGetPointer(chk) \ - ((AllocPointer)(((char *)(chk)) + ALLOC_CHUNKHDRSZ)) +/* + * We always store external chunks on a dedicated block. This makes fetching + * the block from an external chunk easy since it's always the first and only + * chunk on the block. + */ +#define ExternalChunkGetBlock(chunk) (AllocBlock) ((char *) chunk - ALLOC_BLOCKHDRSZ) /* * Rather than repeatedly creating and deleting memory contexts, we keep some @@ -260,42 +256,6 @@ static AllocSetFreeList context_freelists[2] = } }; -/* - * These functions implement the MemoryContext API for AllocSet contexts. - */ -static void *AllocSetAlloc(MemoryContext context, Size size); -static void AllocSetFree(MemoryContext context, void *pointer); -static void *AllocSetRealloc(MemoryContext context, void *pointer, Size size); -static void AllocSetReset(MemoryContext context); -static void AllocSetDelete(MemoryContext context); -static Size AllocSetGetChunkSpace(MemoryContext context, void *pointer); -static bool AllocSetIsEmpty(MemoryContext context); -static void AllocSetStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); - -#ifdef MEMORY_CONTEXT_CHECKING -static void AllocSetCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for AllocSet contexts. - */ -static const MemoryContextMethods AllocSetMethods = { - AllocSetAlloc, - AllocSetFree, - AllocSetRealloc, - AllocSetReset, - AllocSetDelete, - AllocSetGetChunkSpace, - AllocSetIsEmpty, - AllocSetStats -#ifdef MEMORY_CONTEXT_CHECKING - ,AllocSetCheck -#endif -}; - /* ---------- * AllocSetFreeIndex - @@ -387,18 +347,24 @@ AllocSetContextCreateInternal(MemoryContext parent, AllocSet set; AllocBlock block; - /* Assert we padded AllocChunkData properly */ + /* ensure MemoryChunk's size is properly maxaligned */ StaticAssertStmt(ALLOC_CHUNKHDRSZ == MAXALIGN(ALLOC_CHUNKHDRSZ), - "sizeof(AllocChunkData) is not maxaligned"); - StaticAssertStmt(offsetof(AllocChunkData, aset) + sizeof(MemoryContext) == - ALLOC_CHUNKHDRSZ, - "padding calculation in AllocChunkData is wrong"); + "sizeof(MemoryChunk) is not maxaligned"); + /* check we have enough space to store the freelist link */ + StaticAssertStmt(sizeof(AllocFreelistLink) <= (1 << ALLOC_MINBITS), + "sizeof(AllocFreelistLink) larger than minimum allocation size"); /* * First, validate allocation parameters. Once these were regular runtime * test and elog's, but in practice Asserts seem sufficient because nobody * varies their parameters at runtime. We somewhat arbitrarily enforce a - * minimum 1K block size. + * minimum 1K block size. We restrict the maximum block size to + * MEMORYCHUNK_MAX_BLOCKOFFSET as MemoryChunks are limited to this in + * regards to addressing the offset between the chunk and the block that + * the chunk is stored on. We would be unable to store the offset between + * the chunk and block for any chunks that were beyond + * MEMORYCHUNK_MAX_BLOCKOFFSET bytes into the block if the block was to be + * larger than this. */ Assert(initBlockSize == MAXALIGN(initBlockSize) && initBlockSize >= 1024); @@ -409,6 +375,7 @@ AllocSetContextCreateInternal(MemoryContext parent, (minContextSize == MAXALIGN(minContextSize) && minContextSize >= 1024 && minContextSize <= maxBlockSize)); + Assert(maxBlockSize <= MEMORYCHUNK_MAX_BLOCKOFFSET); /* * Check whether the parameters match either available freelist. We do @@ -443,7 +410,7 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Reinitialize its header, installing correct name and parent */ MemoryContextCreate((MemoryContext) set, T_AllocSetContext, - &AllocSetMethods, + MCTX_ASET_ID, parent, name); @@ -519,7 +486,8 @@ AllocSetContextCreateInternal(MemoryContext parent, * * We have to have allocChunkLimit a power of two, because the requested * and actually-allocated sizes of any chunk must be on the same side of - * the limit, else we get confused about whether the chunk is "big". + * the limit, else we get confused about whether the chunk is on a + * dedicated block. * * Also, allocChunkLimit must not exceed ALLOCSET_SEPARATE_THRESHOLD. */ @@ -534,7 +502,7 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) set, T_AllocSetContext, - &AllocSetMethods, + MCTX_ASET_ID, parent, name); @@ -555,7 +523,7 @@ AllocSetContextCreateInternal(MemoryContext parent, * thrash malloc() when a context is repeatedly reset after small allocations, * which is typical behavior for per-tuple contexts. */ -static void +void AllocSetReset(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -623,7 +591,7 @@ AllocSetReset(MemoryContext context) * * Unlike AllocSetReset, this *must* free all resources of the set. */ -static void +void AllocSetDelete(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -717,12 +685,12 @@ AllocSetDelete(MemoryContext context) * is marked, as mcxt.c will set it to UNDEFINED. In some paths we will * return space that is marked NOACCESS - AllocSetRealloc has to beware! */ -static void * +void * AllocSetAlloc(MemoryContext context, Size size) { AllocSet set = (AllocSet) context; AllocBlock block; - AllocChunk chunk; + MemoryChunk *chunk; int fidx; Size chunk_size; Size blksize; @@ -746,18 +714,20 @@ AllocSetAlloc(MemoryContext context, Size size) block->aset = set; block->freeptr = block->endptr = ((char *) block) + blksize; - chunk = (AllocChunk) (((char *) block) + ALLOC_BLOCKHDRSZ); - chunk->aset = set; - chunk->size = chunk_size; + chunk = (MemoryChunk *) (((char *) block) + ALLOC_BLOCKHDRSZ); + + /* mark the MemoryChunk as externally managed */ + MemoryChunkSetHdrMaskExternal(chunk, MCTX_ASET_ID); + #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk_size) - set_sentinel(AllocChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* @@ -780,13 +750,13 @@ AllocSetAlloc(MemoryContext context, Size size) } /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -799,37 +769,43 @@ AllocSetAlloc(MemoryContext context, Size size) chunk = set->freelist[fidx]; if (chunk != NULL) { - Assert(chunk->size >= size); + AllocFreelistLink *link; - set->freelist[fidx] = (AllocChunk) chunk->aset; + Assert(fidx == MemoryChunkGetValue(chunk)); - chunk->aset = (void *) set; + chunk_size = GetChunkSizeFromFreelistIdx(fidx); + link = GetFreeListLink(chunk, chunk_size); + + /* pop this chunk off the freelist */ + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + set->freelist[fidx] = link->next; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(AllocChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, - chunk->size - size); + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, + chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * Choose the actual chunk size to allocate. */ - chunk_size = (1 << ALLOC_MINBITS) << fidx; + chunk_size = GetChunkSizeFromFreelistIdx(fidx); Assert(chunk_size >= size); /* @@ -856,6 +832,7 @@ AllocSetAlloc(MemoryContext context, Size size) */ while (availspace >= ((1 << ALLOC_MINBITS) + ALLOC_CHUNKHDRSZ)) { + AllocFreelistLink *link; Size availchunk = availspace - ALLOC_CHUNKHDRSZ; int a_fidx = AllocSetFreeIndex(availchunk); @@ -864,29 +841,34 @@ AllocSetAlloc(MemoryContext context, Size size) * freelist than the one we need to put this chunk on. The * exception is when availchunk is exactly a power of 2. */ - if (availchunk != ((Size) 1 << (a_fidx + ALLOC_MINBITS))) + if (availchunk != GetChunkSizeFromFreelistIdx(a_fidx)) { a_fidx--; Assert(a_fidx >= 0); - availchunk = ((Size) 1 << (a_fidx + ALLOC_MINBITS)); + availchunk = GetChunkSizeFromFreelistIdx(a_fidx); } - chunk = (AllocChunk) (block->freeptr); + chunk = (MemoryChunk *) (block->freeptr); /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, ALLOC_CHUNKHDRSZ); - block->freeptr += (availchunk + ALLOC_CHUNKHDRSZ); availspace -= (availchunk + ALLOC_CHUNKHDRSZ); - chunk->size = availchunk; + /* store the freelist index in the value field */ + MemoryChunkSetHdrMask(chunk, block, a_fidx, MCTX_ASET_ID); #ifdef MEMORY_CONTEXT_CHECKING - chunk->requested_size = 0; /* mark it free */ + chunk->requested_size = InvalidAllocSize; /* mark it free */ #endif - chunk->aset = (void *) set->freelist[a_fidx]; + /* push this chunk onto the freelist */ + link = GetFreeListLink(chunk, availchunk); + + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + link->next = set->freelist[a_fidx]; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); + set->freelist[a_fidx] = chunk; } - /* Mark that we need to create a new block */ block = NULL; } @@ -954,7 +936,7 @@ AllocSetAlloc(MemoryContext context, Size size) /* * OK, do the allocation */ - chunk = (AllocChunk) (block->freeptr); + chunk = (MemoryChunk *) (block->freeptr); /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, ALLOC_CHUNKHDRSZ); @@ -962,67 +944,68 @@ AllocSetAlloc(MemoryContext context, Size size) block->freeptr += (chunk_size + ALLOC_CHUNKHDRSZ); Assert(block->freeptr <= block->endptr); - chunk->aset = (void *) set; - chunk->size = chunk_size; + /* store the freelist index in the value field */ + MemoryChunkSetHdrMask(chunk, block, fidx, MCTX_ASET_ID); + #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(AllocChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * AllocSetFree * Frees allocated memory; memory is removed from the set. */ -static void -AllocSetFree(MemoryContext context, void *pointer) +void +AllocSetFree(void *pointer) { - AllocSet set = (AllocSet) context; - AllocChunk chunk = AllocPointerGetChunk(pointer); + AllocSet set; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); + if (MemoryChunkIsExternal(chunk)) + { + + AllocBlock block = ExternalChunkGetBlock(chunk); + + set = block->aset; + #ifdef MEMORY_CONTEXT_CHECKING - /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunk->size) - if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", - set->header.name, chunk); + { + Size chunk_size = block->endptr - (char *) pointer; + + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < chunk_size) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); + } #endif - if (chunk->size > set->allocChunkLimit) - { - /* - * Big chunks are certain to have been allocated as single-chunk - * blocks. Just unlink that block and return it to malloc(). - */ - AllocBlock block = (AllocBlock) (((char *) chunk) - ALLOC_BLOCKHDRSZ); /* - * Try to verify that we have a sane block pointer: it should - * reference the correct aset, and freeptr and endptr should point - * just past the chunk. + * Try to verify that we have a sane block pointer, the freeptr should + * match the endptr. */ - if (block->aset != set || - block->freeptr != block->endptr || - block->freeptr != ((char *) block) + - (chunk->size + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) + if (block->freeptr != block->endptr) elog(ERROR, "could not find block containing chunk %p", chunk); /* OK, remove block from aset's list and free it */ @@ -1033,7 +1016,7 @@ AllocSetFree(MemoryContext context, void *pointer) if (block->next) block->next->prev = block->prev; - context->mem_allocated -= block->endptr - ((char *) block); + set->header.mem_allocated -= block->endptr - ((char *) block); #ifdef CLOBBER_FREED_MEMORY wipe_mem(block, block->freeptr - ((char *) block)); @@ -1042,20 +1025,38 @@ AllocSetFree(MemoryContext context, void *pointer) } else { - /* Normal case, put the chunk into appropriate freelist */ - int fidx = AllocSetFreeIndex(chunk->size); + int fidx = MemoryChunkGetValue(chunk); + AllocBlock block = MemoryChunkGetBlock(chunk); + Size chunk_size = GetChunkSizeFromFreelistIdx(fidx); + AllocFreelistLink *link = GetFreeListLink(chunk, chunk_size); - chunk->aset = (void *) set->freelist[fidx]; + set = block->aset; + +#ifdef MEMORY_CONTEXT_CHECKING + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < chunk_size) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); +#endif #ifdef CLOBBER_FREED_MEMORY - wipe_mem(pointer, chunk->size); + wipe_mem(pointer, chunk_size); #endif + /* Normal case, put the chunk into appropriate freelist */ + /* push this chunk onto the top of the freelist for this chunk size */ + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + link->next = set->freelist[fidx]; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); + set->freelist[fidx] = chunk; #ifdef MEMORY_CONTEXT_CHECKING - /* Reset requested_size to 0 in chunks that are on freelist */ - chunk->requested_size = 0; + /* + * Reset requested_size to InvalidAllocSize in chunks that are on + * freelist. + */ + chunk->requested_size = InvalidAllocSize; #endif - set->freelist[fidx] = chunk; } } @@ -1071,57 +1072,48 @@ AllocSetFree(MemoryContext context, void *pointer) * (In principle, we could use VALGRIND_GET_VBITS() to rediscover the old * request size.) */ -static void * -AllocSetRealloc(MemoryContext context, void *pointer, Size size) +void * +AllocSetRealloc(void *pointer, Size size) { - AllocSet set = (AllocSet) context; - AllocChunk chunk = AllocPointerGetChunk(pointer); + AllocBlock block; + AllocSet set; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); Size oldsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - oldsize = chunk->size; - -#ifdef MEMORY_CONTEXT_CHECKING - /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < oldsize) - if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", - set->header.name, chunk); -#endif - - if (oldsize > set->allocChunkLimit) + if (MemoryChunkIsExternal(chunk)) { /* * The chunk must have been allocated as a single-chunk block. Use * realloc() to make the containing block bigger, or smaller, with * minimum space wastage. */ - AllocBlock block = (AllocBlock) (((char *) chunk) - ALLOC_BLOCKHDRSZ); Size chksize; Size blksize; Size oldblksize; + block = ExternalChunkGetBlock(chunk); + oldsize = block->endptr - (char *) pointer; + set = block->aset; + +#ifdef MEMORY_CONTEXT_CHECKING + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < oldsize) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); +#endif + /* - * Try to verify that we have a sane block pointer: it should - * reference the correct aset, and freeptr and endptr should point - * just past the chunk. + * Try to verify that we have a sane block pointer, the freeptr should + * match the endptr. */ - if (block->aset != set || - block->freeptr != block->endptr || - block->freeptr != ((char *) block) + - (oldsize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) + if (block->freeptr != block->endptr) elog(ERROR, "could not find block containing chunk %p", chunk); - /* - * Even if the new request is less than set->allocChunkLimit, we stick - * with the single-chunk block approach. Therefore we need - * chunk->size to be bigger than set->allocChunkLimit, so we don't get - * confused about the chunk's status in future calls. - */ - chksize = Max(size, set->allocChunkLimit + 1); - chksize = MAXALIGN(chksize); + chksize = MAXALIGN(size); /* Do the realloc */ blksize = chksize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ; @@ -1136,21 +1128,20 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) } /* updated separately, not to underflow when (oldblksize > blksize) */ - context->mem_allocated -= oldblksize; - context->mem_allocated += blksize; + set->header.mem_allocated -= oldblksize; + set->header.mem_allocated += blksize; block->freeptr = block->endptr = ((char *) block) + blksize; /* Update pointers since block has likely been moved */ - chunk = (AllocChunk) (((char *) block) + ALLOC_BLOCKHDRSZ); - pointer = AllocChunkGetPointer(chunk); + chunk = (MemoryChunk *) (((char *) block) + ALLOC_BLOCKHDRSZ); + pointer = MemoryChunkGetPointer(chunk); if (block->prev) block->prev->next = block; else set->blocks = block; if (block->next) block->next->prev = block; - chunk->size = chksize; #ifdef MEMORY_CONTEXT_CHECKING #ifdef RANDOMIZE_ALLOCATED_MEMORY @@ -1172,9 +1163,8 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) #endif chunk->requested_size = size; - /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) + if (size < chksize) set_sentinel(pointer, size); #else /* !MEMORY_CONTEXT_CHECKING */ @@ -1195,12 +1185,24 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) return pointer; } + block = MemoryChunkGetBlock(chunk); + oldsize = GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)); + set = block->aset; + +#ifdef MEMORY_CONTEXT_CHECKING + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < oldsize) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); +#endif + /* * Chunk sizes are aligned to power of 2 in AllocSetAlloc(). Maybe the * allocated area already is >= the new size. (In particular, we will * fall out here if the requested size is a decrease.) */ - else if (oldsize >= size) + if (oldsize >= size) { #ifdef MEMORY_CONTEXT_CHECKING Size oldrequest = chunk->requested_size; @@ -1289,34 +1291,59 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) memcpy(newPointer, pointer, oldsize); /* free old chunk */ - AllocSetFree((MemoryContext) set, pointer); + AllocSetFree(pointer); return newPointer; } } +/* + * AllocSetGetChunkContext + * Return the MemoryContext that 'pointer' belongs to. + */ +MemoryContext +AllocSetGetChunkContext(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + AllocBlock block; + AllocSet set; + + if (MemoryChunkIsExternal(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (AllocBlock) MemoryChunkGetBlock(chunk); + + set = block->aset; + + return &set->header; +} + /* * AllocSetGetChunkSpace * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -AllocSetGetChunkSpace(MemoryContext context, void *pointer) +Size +AllocSetGetChunkSpace(void *pointer) { - AllocChunk chunk = AllocPointerGetChunk(pointer); - Size result; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); - VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - result = chunk->size + ALLOC_CHUNKHDRSZ; - VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return result; + if (MemoryChunkIsExternal(chunk)) + { + AllocBlock block = ExternalChunkGetBlock(chunk); + + return block->endptr - (char *) chunk; + } + + return GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)) + + ALLOC_CHUNKHDRSZ; } /* * AllocSetIsEmpty * Is an allocset empty of any allocated space? */ -static bool +bool AllocSetIsEmpty(MemoryContext context) { /* @@ -1339,7 +1366,7 @@ AllocSetIsEmpty(MemoryContext context) * totals: if not NULL, add stats about this context into *totals. * print_to_stderr: print stats to stderr if true, elog otherwise. */ -static void +void AllocSetStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr) @@ -1363,13 +1390,21 @@ AllocSetStats(MemoryContext context, } for (fidx = 0; fidx < ALLOCSET_NUM_FREELISTS; fidx++) { - AllocChunk chunk; + MemoryChunk *chunk = set->freelist[fidx]; - for (chunk = set->freelist[fidx]; chunk != NULL; - chunk = (AllocChunk) chunk->aset) + while (chunk != NULL) { + Size chksz = GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)); + AllocFreelistLink *link = GetFreeListLink(chunk, chksz); + + Assert(GetChunkSizeFromFreelistIdx(fidx) == chksz); + freechunks++; - freespace += chunk->size + ALLOC_CHUNKHDRSZ; + freespace += chksz + ALLOC_CHUNKHDRSZ; + + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + chunk = link->next; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); } } @@ -1404,7 +1439,7 @@ AllocSetStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void AllocSetCheck(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -1421,6 +1456,7 @@ AllocSetCheck(MemoryContext context) long blk_used = block->freeptr - bpoz; long blk_data = 0; long nchunks = 0; + bool has_external_chunk = false; if (set->keeper == block) total_allocated += block->endptr - ((char *) set); @@ -1452,20 +1488,31 @@ AllocSetCheck(MemoryContext context) */ while (bpoz < block->freeptr) { - AllocChunk chunk = (AllocChunk) bpoz; + MemoryChunk *chunk = (MemoryChunk *) bpoz; + AllocBlock chunkblock; Size chsize, dsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - chsize = chunk->size; /* aligned chunk size */ + if (MemoryChunkIsExternal(chunk)) + { + chsize = block->endptr - (char *) MemoryChunkGetPointer(chunk); /* aligned chunk size */ + chunkblock = ExternalChunkGetBlock(chunk); + has_external_chunk = true; + } + else + { + chsize = GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)); /* aligned chunk size */ + chunkblock = (AllocBlock) MemoryChunkGetBlock(chunk); + } dsize = chunk->requested_size; /* real data */ /* * Check chunk size */ - if (dsize > chsize) + if (dsize != InvalidAllocSize && dsize > chsize) elog(WARNING, "problem in alloc set %s: req size > alloc size for chunk %p in block %p", name, chunk, block); if (chsize < (1 << ALLOC_MINBITS)) @@ -1478,20 +1525,15 @@ AllocSetCheck(MemoryContext context) elog(WARNING, "problem in alloc set %s: bad single-chunk %p in block %p", name, chunk, block); - /* - * If chunk is allocated, check for correct aset pointer. (If it's - * free, the aset is the freelist pointer, which we can't check as - * easily...) Note this is an incomplete test, since palloc(0) - * produces an allocated chunk with requested_size == 0. - */ - if (dsize > 0 && chunk->aset != (void *) set) - elog(WARNING, "problem in alloc set %s: bogus aset link in block %p, chunk %p", - name, block, chunk); + /* Check the block offset correctly matches this block */ + if (block != chunkblock) + elog(WARNING, "problem in alloc set %s: bad block offset for chunk %p in block %p", + name, chunk, block); /* * Check for overwrite of padding space in an allocated chunk. */ - if (chunk->aset == (void *) set && dsize < chsize && + if (dsize != InvalidAllocSize && dsize < chsize && !sentinel_ok(chunk, ALLOC_CHUNKHDRSZ + dsize)) elog(WARNING, "problem in alloc set %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); @@ -1500,7 +1542,7 @@ AllocSetCheck(MemoryContext context) * If chunk is allocated, disallow external access to private part * of chunk header. */ - if (chunk->aset == (void *) set) + if (dsize != InvalidAllocSize) VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); blk_data += chsize; @@ -1512,6 +1554,10 @@ AllocSetCheck(MemoryContext context) if ((blk_data + (nchunks * ALLOC_CHUNKHDRSZ)) != blk_used) elog(WARNING, "problem in alloc set %s: found inconsistent memory block %p", name, block); + + if (has_external_chunk && nchunks > 1) + elog(WARNING, "problem in alloc set %s: external chunk on non-dedicated block %p", + name, block); } Assert(total_allocated == context->mem_allocated); diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index e530e272e0..9ad4b9fcfb 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -39,15 +39,16 @@ #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" #define Generation_BLOCKHDRSZ MAXALIGN(sizeof(GenerationBlock)) -#define Generation_CHUNKHDRSZ sizeof(GenerationChunk) +#define Generation_CHUNKHDRSZ sizeof(MemoryChunk) #define Generation_CHUNK_FRACTION 8 typedef struct GenerationBlock GenerationBlock; /* forward reference */ -typedef struct GenerationChunk GenerationChunk; typedef void *GenerationPointer; @@ -89,6 +90,7 @@ typedef struct GenerationContext struct GenerationBlock { dlist_node node; /* doubly-linked list of blocks */ + GenerationContext *context; /* pointer back to the owning context */ Size blksize; /* allocated size of this block */ int nchunks; /* number of chunks in the block */ int nfree; /* number of free chunks */ @@ -97,104 +99,36 @@ struct GenerationBlock }; /* - * GenerationChunk - * The prefix of each piece of memory in a GenerationBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "context" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). We simplify matters for this - * module by requiring sizeof(GenerationChunk) to be maxaligned, and then - * we can ensure things work by adding any required alignment padding before - * the pointer fields. There is a static assertion below that the alignment - * is done correctly. - */ -struct GenerationChunk -{ - /* size is always the size of the usable space in the chunk */ - Size size; -#ifdef MEMORY_CONTEXT_CHECKING - /* when debugging memory usage, also store actual requested size */ - /* this is zero in a free chunk */ - Size requested_size; - -#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T * 2 + SIZEOF_VOID_P * 2) -#else -#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P * 2) -#endif /* MEMORY_CONTEXT_CHECKING */ - - /* ensure proper alignment by adding padding if needed */ -#if (GENERATIONCHUNK_RAWSIZE % MAXIMUM_ALIGNOF) != 0 - char padding[MAXIMUM_ALIGNOF - GENERATIONCHUNK_RAWSIZE % MAXIMUM_ALIGNOF]; -#endif - - GenerationBlock *block; /* block owning this chunk */ - GenerationContext *context; /* owning context, or NULL if freed chunk */ - /* there must not be any padding to reach a MAXALIGN boundary here! */ -}; - -/* - * Only the "context" field should be accessed outside this module. + * Only the "hdrmask" field should be accessed outside this module. * We keep the rest of an allocated chunk's header marked NOACCESS when using * valgrind. But note that freed chunk headers are kept accessible, for * simplicity. */ -#define GENERATIONCHUNK_PRIVATE_LEN offsetof(GenerationChunk, context) - +#define GENERATIONCHUNK_PRIVATE_LEN offsetof(MemoryChunk, hdrmask) /* * GenerationIsValid * True iff set is valid allocation set. */ #define GenerationIsValid(set) PointerIsValid(set) -#define GenerationPointerGetChunk(ptr) \ - ((GenerationChunk *)(((char *)(ptr)) - Generation_CHUNKHDRSZ)) -#define GenerationChunkGetPointer(chk) \ - ((GenerationPointer *)(((char *)(chk)) + Generation_CHUNKHDRSZ)) +/* + * We always store external chunks on a dedicated block. This makes fetching + * the block from an external chunk easy since it's always the first and only + * chunk on the block. + */ +#define ExternalChunkGetBlock(chunk) \ + (GenerationBlock *) ((char *) chunk - Generation_BLOCKHDRSZ) /* Inlined helper functions */ -static inline void GenerationBlockInit(GenerationBlock *block, Size blksize); +static inline void GenerationBlockInit(GenerationContext *context, + GenerationBlock *block, + Size blksize); static inline bool GenerationBlockIsEmpty(GenerationBlock *block); static inline void GenerationBlockMarkEmpty(GenerationBlock *block); static inline Size GenerationBlockFreeBytes(GenerationBlock *block); static inline void GenerationBlockFree(GenerationContext *set, GenerationBlock *block); -/* - * These functions implement the MemoryContext API for Generation contexts. - */ -static void *GenerationAlloc(MemoryContext context, Size size); -static void GenerationFree(MemoryContext context, void *pointer); -static void *GenerationRealloc(MemoryContext context, void *pointer, Size size); -static void GenerationReset(MemoryContext context); -static void GenerationDelete(MemoryContext context); -static Size GenerationGetChunkSpace(MemoryContext context, void *pointer); -static bool GenerationIsEmpty(MemoryContext context); -static void GenerationStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); - -#ifdef MEMORY_CONTEXT_CHECKING -static void GenerationCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for Generation contexts. - */ -static const MemoryContextMethods GenerationMethods = { - GenerationAlloc, - GenerationFree, - GenerationRealloc, - GenerationReset, - GenerationDelete, - GenerationGetChunkSpace, - GenerationIsEmpty, - GenerationStats -#ifdef MEMORY_CONTEXT_CHECKING - ,GenerationCheck -#endif -}; - /* * Public routines @@ -223,17 +157,20 @@ GenerationContextCreate(MemoryContext parent, GenerationContext *set; GenerationBlock *block; - /* Assert we padded GenerationChunk properly */ + /* ensure MemoryChunk's size is properly maxaligned */ StaticAssertStmt(Generation_CHUNKHDRSZ == MAXALIGN(Generation_CHUNKHDRSZ), - "sizeof(GenerationChunk) is not maxaligned"); - StaticAssertStmt(offsetof(GenerationChunk, context) + sizeof(MemoryContext) == - Generation_CHUNKHDRSZ, - "padding calculation in GenerationChunk is wrong"); + "sizeof(MemoryChunk) is not maxaligned"); /* * First, validate allocation parameters. Asserts seem sufficient because * nobody varies their parameters at runtime. We somewhat arbitrarily - * enforce a minimum 1K block size. + * enforce a minimum 1K block size. We restrict the maximum block size to + * MEMORYCHUNK_MAX_BLOCKOFFSET as MemoryChunks are limited to this in + * regards to addressing the offset between the chunk and the block that + * the chunk is stored on. We would be unable to store the offset between + * the chunk and block for any chunks that were beyond + * MEMORYCHUNK_MAX_BLOCKOFFSET bytes into the block if the block was to be + * larger than this. */ Assert(initBlockSize == MAXALIGN(initBlockSize) && initBlockSize >= 1024); @@ -244,6 +181,7 @@ GenerationContextCreate(MemoryContext parent, (minContextSize == MAXALIGN(minContextSize) && minContextSize >= 1024 && minContextSize <= maxBlockSize)); + Assert(maxBlockSize <= MEMORYCHUNK_MAX_BLOCKOFFSET); /* Determine size of initial block */ allocSize = MAXALIGN(sizeof(GenerationContext)) + @@ -278,7 +216,7 @@ GenerationContextCreate(MemoryContext parent, block = (GenerationBlock *) (((char *) set) + MAXALIGN(sizeof(GenerationContext))); /* determine the block size and initialize it */ firstBlockSize = allocSize - MAXALIGN(sizeof(GenerationContext)); - GenerationBlockInit(block, firstBlockSize); + GenerationBlockInit(set, block, firstBlockSize); /* add it to the doubly-linked list of blocks */ dlist_push_head(&set->blocks, &block->node); @@ -300,9 +238,14 @@ GenerationContextCreate(MemoryContext parent, /* * Compute the allocation chunk size limit for this context. * - * Follows similar ideas as AllocSet, see aset.c for details ... + * Limit the maximum size a non-dedicated chunk can be so that we can fit + * at least Generation_CHUNK_FRACTION of chunks this big onto the maximum + * sized block. We must further limit this value so that it's no more + * than MEMORYCHUNK_MAX_VALUE. We're unable to have non-dedicated chunks + * larger than that value as we store the chunk size in the MemoryChunk + * 'value' field in the call to MemoryChunkSetHdrMask(). */ - set->allocChunkLimit = maxBlockSize; + set->allocChunkLimit = Min(maxBlockSize, MEMORYCHUNK_MAX_VALUE); while ((Size) (set->allocChunkLimit + Generation_CHUNKHDRSZ) > (Size) ((Size) (maxBlockSize - Generation_BLOCKHDRSZ) / Generation_CHUNK_FRACTION)) set->allocChunkLimit >>= 1; @@ -310,7 +253,7 @@ GenerationContextCreate(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) set, T_GenerationContext, - &GenerationMethods, + MCTX_GENERATION_ID, parent, name); @@ -326,7 +269,7 @@ GenerationContextCreate(MemoryContext parent, * The code simply frees all the blocks in the context - we don't keep any * keeper blocks or anything like that. */ -static void +void GenerationReset(MemoryContext context) { GenerationContext *set = (GenerationContext *) context; @@ -371,7 +314,7 @@ GenerationReset(MemoryContext context) * GenerationDelete * Free all memory which is allocated in the given context. */ -static void +void GenerationDelete(MemoryContext context) { /* Reset to release all releasable GenerationBlocks */ @@ -393,12 +336,12 @@ GenerationDelete(MemoryContext context) * is marked, as mcxt.c will set it to UNDEFINED. In some paths we will * return space that is marked NOACCESS - GenerationRealloc has to beware! */ -static void * +void * GenerationAlloc(MemoryContext context, Size size) { GenerationContext *set = (GenerationContext *) context; GenerationBlock *block; - GenerationChunk *chunk; + MemoryChunk *chunk; Size chunk_size = MAXALIGN(size); Size required_size = chunk_size + Generation_CHUNKHDRSZ; @@ -414,6 +357,7 @@ GenerationAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; /* block with a single (used) chunk */ + block->context = set; block->blksize = blksize; block->nchunks = 1; block->nfree = 0; @@ -421,33 +365,33 @@ GenerationAlloc(MemoryContext context, Size size) /* the block is completely full */ block->freeptr = block->endptr = ((char *) block) + blksize; - chunk = (GenerationChunk *) (((char *) block) + Generation_BLOCKHDRSZ); - chunk->block = block; - chunk->context = set; - chunk->size = chunk_size; + chunk = (MemoryChunk *) (((char *) block) + Generation_BLOCKHDRSZ); + + /* mark the MemoryChunk as externally managed */ + MemoryChunkSetHdrMaskExternal(chunk, MCTX_GENERATION_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk_size) - set_sentinel(GenerationChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) GenerationChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* add the block to the list of allocated blocks */ dlist_push_head(&set->blocks, &block->node); /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) GenerationChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return GenerationChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -516,7 +460,7 @@ GenerationAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; /* initialize the new block */ - GenerationBlockInit(block, blksize); + GenerationBlockInit(set, block, blksize); /* add it to the doubly-linked list of blocks */ dlist_push_head(&set->blocks, &block->node); @@ -533,7 +477,7 @@ GenerationAlloc(MemoryContext context, Size size) Assert(block != NULL); Assert((block->endptr - block->freeptr) >= Generation_CHUNKHDRSZ + chunk_size); - chunk = (GenerationChunk *) block->freeptr; + chunk = (MemoryChunk *) block->freeptr; /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, Generation_CHUNKHDRSZ); @@ -543,29 +487,26 @@ GenerationAlloc(MemoryContext context, Size size) Assert(block->freeptr <= block->endptr); - chunk->block = block; - chunk->context = set; - chunk->size = chunk_size; - + MemoryChunkSetHdrMask(chunk, block, chunk_size, MCTX_GENERATION_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(GenerationChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) GenerationChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) GenerationChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return GenerationChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -574,8 +515,10 @@ GenerationAlloc(MemoryContext context, Size size) * mem_allocated field. */ static inline void -GenerationBlockInit(GenerationBlock *block, Size blksize) +GenerationBlockInit(GenerationContext *context, GenerationBlock *block, + Size blksize) { + block->context = context; block->blksize = blksize; block->nchunks = 0; block->nfree = 0; @@ -661,36 +604,49 @@ GenerationBlockFree(GenerationContext *set, GenerationBlock *block) * Update number of chunks in the block, and if all chunks in the block * are now free then discard the block. */ -static void -GenerationFree(MemoryContext context, void *pointer) +void +GenerationFree(void *pointer) { - GenerationContext *set = (GenerationContext *) context; - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); GenerationBlock *block; + GenerationContext *set; +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + Size chunksize; +#endif + + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + chunksize = block->endptr - (char *) pointer; +#endif + } + else + { + block = MemoryChunkGetBlock(chunk); +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + chunksize = MemoryChunkGetValue(chunk); +#endif + } /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - block = chunk->block; - #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunk->size) + if (chunk->requested_size < chunksize) if (!sentinel_ok(pointer, chunk->requested_size)) elog(WARNING, "detected write past chunk end in %s %p", - ((MemoryContext) set)->name, chunk); + ((MemoryContext) block->context)->name, chunk); #endif #ifdef CLOBBER_FREED_MEMORY - wipe_mem(pointer, chunk->size); + wipe_mem(pointer, chunksize); #endif - /* Reset context to NULL in freed chunks */ - chunk->context = NULL; - #ifdef MEMORY_CONTEXT_CHECKING - /* Reset requested_size to 0 in freed chunks */ - chunk->requested_size = 0; + /* Reset requested_size to InvalidAllocSize in freed chunks */ + chunk->requested_size = InvalidAllocSize; #endif block->nfree += 1; @@ -702,6 +658,8 @@ GenerationFree(MemoryContext context, void *pointer) if (block->nfree < block->nchunks) return; + set = block->context; + /* Don't try to free the keeper block, just mark it empty */ if (block == set->keeper) { @@ -732,7 +690,7 @@ GenerationFree(MemoryContext context, void *pointer) */ dlist_delete(&block->node); - context->mem_allocated -= block->blksize; + set->header.mem_allocated -= block->blksize; free(block); } @@ -742,18 +700,30 @@ GenerationFree(MemoryContext context, void *pointer) * and discard the old one. The only exception is when the new size fits * into the old chunk - in that case we just update chunk header. */ -static void * -GenerationRealloc(MemoryContext context, void *pointer, Size size) +void * +GenerationRealloc(void *pointer, Size size) { - GenerationContext *set = (GenerationContext *) context; - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationContext *set; + GenerationBlock *block; GenerationPointer newPointer; Size oldsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - oldsize = chunk->size; + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); + oldsize = block->endptr - (char *) pointer; + } + else + { + block = MemoryChunkGetBlock(chunk); + oldsize = MemoryChunkGetValue(chunk); + } + + set = block->context; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ @@ -848,7 +818,7 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) memcpy(newPointer, pointer, oldsize); /* free old chunk */ - GenerationFree((MemoryContext) set, pointer); + GenerationFree(pointer); return newPointer; } @@ -858,23 +828,47 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -GenerationGetChunkSpace(MemoryContext context, void *pointer) +MemoryContext +GenerationGetChunkContext(void *pointer) { - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); - Size result; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationBlock *block; - VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - result = chunk->size + Generation_CHUNKHDRSZ; - VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return result; + if (MemoryChunkIsExternal(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (GenerationBlock *) MemoryChunkGetBlock(chunk); + + return &block->context->header; +} + +/* + * GenerationGetChunkSpace + * Given a currently-allocated chunk, determine the total space + * it occupies (including all memory-allocation overhead). + */ +Size +GenerationGetChunkSpace(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + Size chunksize; + + if (MemoryChunkIsExternal(chunk)) + { + GenerationBlock *block = ExternalChunkGetBlock(chunk); + chunksize = block->endptr - (char *) pointer; + } + else + chunksize = MemoryChunkGetValue(chunk); + + return Generation_CHUNKHDRSZ + chunksize; } /* * GenerationIsEmpty * Is a GenerationContext empty of any allocated space? */ -static bool +bool GenerationIsEmpty(MemoryContext context) { GenerationContext *set = (GenerationContext *) context; @@ -903,7 +897,7 @@ GenerationIsEmpty(MemoryContext context) * XXX freespace only accounts for empty space at the end of the block, not * space of freed chunks (which is unknown). */ -static void +void GenerationStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr) @@ -961,7 +955,7 @@ GenerationStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void GenerationCheck(MemoryContext context) { GenerationContext *gen = (GenerationContext *) context; @@ -976,6 +970,7 @@ GenerationCheck(MemoryContext context) int nfree, nchunks; char *ptr; + bool has_external_chunk = false; total_allocated += block->blksize; @@ -987,6 +982,11 @@ GenerationCheck(MemoryContext context) elog(WARNING, "problem in Generation %s: number of free chunks %d in block %p exceeds %d allocated", name, block->nfree, block, block->nchunks); + /* check block belongs to the correct context */ + if (block->context != gen) + elog(WARNING, "problem in Generation %s: bogus context link in block %p", + name, block); + /* Now walk through the chunks and count them. */ nfree = 0; nchunks = 0; @@ -994,42 +994,47 @@ GenerationCheck(MemoryContext context) while (ptr < block->freeptr) { - GenerationChunk *chunk = (GenerationChunk *) ptr; + MemoryChunk *chunk = (MemoryChunk *) ptr; + GenerationBlock *chunkblock; + Size chunksize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); + if (MemoryChunkIsExternal(chunk)) + { + chunkblock = ExternalChunkGetBlock(chunk); + chunksize = block->endptr - (char *) MemoryChunkGetPointer(chunk); + has_external_chunk = true; + } + else + { + chunkblock = MemoryChunkGetBlock(chunk); + chunksize = MemoryChunkGetValue(chunk); + } + /* move to the next chunk */ - ptr += (chunk->size + Generation_CHUNKHDRSZ); + ptr += (chunksize + Generation_CHUNKHDRSZ); nchunks += 1; /* chunks have both block and context pointers, so check both */ - if (chunk->block != block) + if (chunkblock != block) elog(WARNING, "problem in Generation %s: bogus block link in block %p, chunk %p", name, block, chunk); - /* - * Check for valid context pointer. Note this is an incomplete - * test, since palloc(0) produces an allocated chunk with - * requested_size == 0. - */ - if ((chunk->requested_size > 0 && chunk->context != gen) || - (chunk->context != gen && chunk->context != NULL)) - elog(WARNING, "problem in Generation %s: bogus context link in block %p, chunk %p", - name, block, chunk); - - /* now make sure the chunk size is correct */ - if (chunk->size < chunk->requested_size || - chunk->size != MAXALIGN(chunk->size)) - elog(WARNING, "problem in Generation %s: bogus chunk size in block %p, chunk %p", - name, block, chunk); /* is chunk allocated? */ - if (chunk->context != NULL) + if (chunk->requested_size != InvalidAllocSize) { - /* check sentinel, but only in allocated blocks */ - if (chunk->requested_size < chunk->size && + /* now make sure the chunk size is correct */ + if (chunksize < chunk->requested_size || + chunksize != MAXALIGN(chunksize)) + elog(WARNING, "problem in Generation %s: bogus chunk size in block %p, chunk %p", + name, block, chunk); + + /* check sentinel */ + if (chunk->requested_size < chunksize && !sentinel_ok(chunk, Generation_CHUNKHDRSZ + chunk->requested_size)) elog(WARNING, "problem in Generation %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); @@ -1041,7 +1046,7 @@ GenerationCheck(MemoryContext context) * If chunk is allocated, disallow external access to private part * of chunk header. */ - if (chunk->context != NULL) + if (chunk->requested_size != InvalidAllocSize) VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); } @@ -1056,6 +1061,11 @@ GenerationCheck(MemoryContext context) if (nfree != block->nfree) elog(WARNING, "problem in Generation %s: number of free chunks %d in block %p does not match header %d", name, nfree, block, block->nfree); + + if (has_external_chunk && nchunks > 1) + elog(WARNING, "problem in Generation %s: external chunk on non-dedicated block %p", + name, block); + } Assert(total_allocated == context->mem_allocated); diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index e12be1b9bd..7c53222b9d 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -29,12 +29,57 @@ #include "utils/fmgrprotos.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_internal.h" /***************************************************************************** * GLOBAL MEMORY * *****************************************************************************/ +static const MemoryContextMethods mcxt_methods[] = { + /* aset.c */ + [MCTX_ASET_ID].alloc = AllocSetAlloc, + [MCTX_ASET_ID].free_p = AllocSetFree, + [MCTX_ASET_ID].realloc = AllocSetRealloc, + [MCTX_ASET_ID].reset = AllocSetReset, + [MCTX_ASET_ID].delete_context = AllocSetDelete, + [MCTX_ASET_ID].get_chunk_context = AllocSetGetChunkContext, + [MCTX_ASET_ID].get_chunk_space = AllocSetGetChunkSpace, + [MCTX_ASET_ID].is_empty = AllocSetIsEmpty, + [MCTX_ASET_ID].stats = AllocSetStats, +#ifdef MEMORY_CONTEXT_CHECKING + [MCTX_ASET_ID].check = AllocSetCheck, +#endif + + /* generation.c */ + [MCTX_GENERATION_ID].alloc = GenerationAlloc, + [MCTX_GENERATION_ID].free_p = GenerationFree, + [MCTX_GENERATION_ID].realloc = GenerationRealloc, + [MCTX_GENERATION_ID].reset = GenerationReset, + [MCTX_GENERATION_ID].delete_context = GenerationDelete, + [MCTX_GENERATION_ID].get_chunk_context = GenerationGetChunkContext, + [MCTX_GENERATION_ID].get_chunk_space = GenerationGetChunkSpace, + [MCTX_GENERATION_ID].is_empty = GenerationIsEmpty, + [MCTX_GENERATION_ID].stats = GenerationStats, +#ifdef MEMORY_CONTEXT_CHECKING + [MCTX_GENERATION_ID].check = GenerationCheck, +#endif + + /* slab.c */ + [MCTX_SLAB_ID].alloc = SlabAlloc, + [MCTX_SLAB_ID].free_p = SlabFree, + [MCTX_SLAB_ID].realloc = SlabRealloc, + [MCTX_SLAB_ID].reset = SlabReset, + [MCTX_SLAB_ID].delete_context = SlabDelete, + [MCTX_SLAB_ID].get_chunk_context = SlabGetChunkContext, + [MCTX_SLAB_ID].get_chunk_space = SlabGetChunkSpace, + [MCTX_SLAB_ID].is_empty = SlabIsEmpty, + [MCTX_SLAB_ID].stats = SlabStats +#ifdef MEMORY_CONTEXT_CHECKING + ,[MCTX_SLAB_ID].check = SlabCheck +#endif +}; + /* * CurrentMemoryContext * Default memory context for allocations. @@ -73,6 +118,13 @@ static void MemoryContextStatsPrint(MemoryContext context, void *passthru, #define AssertNotInCriticalSection(context) \ Assert(CritSectionCount == 0 || (context)->allowInCritSection) +/* + * Call the given function in the MemoryContextMethods for the memory context + * type that 'pointer' belongs to. + */ +#define MCXT_METHOD(pointer, method) \ + mcxt_methods[GetMemoryChunkMethodID(pointer)].method + /***************************************************************************** * EXPORTED ROUTINES * @@ -422,6 +474,17 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) context->allowInCritSection = allow; } +/* + * GetMemoryChunkContext + * Given a currently-allocated chunk, determine the MemoryContext that + * the chunk belongs to. + */ +MemoryContext +GetMemoryChunkContext(void *pointer) +{ + return MCXT_METHOD(pointer, get_chunk_context) (pointer); +} + /* * GetMemoryChunkSpace * Given a currently-allocated chunk, determine the total space @@ -433,9 +496,7 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) Size GetMemoryChunkSpace(void *pointer) { - MemoryContext context = GetMemoryChunkContext(pointer); - - return context->methods->get_chunk_space(context, pointer); + return MCXT_METHOD(pointer, get_chunk_space) (pointer); } /* @@ -814,7 +875,7 @@ MemoryContextContains(MemoryContext context, void *pointer) void MemoryContextCreate(MemoryContext node, NodeTag tag, - const MemoryContextMethods *methods, + MemoryContextMethodID method_id, MemoryContext parent, const char *name) { @@ -824,7 +885,7 @@ MemoryContextCreate(MemoryContext node, /* Initialize all standard fields of memory context header */ node->type = tag; node->isReset = true; - node->methods = methods; + node->methods = &mcxt_methods[method_id]; node->parent = parent; node->firstchild = NULL; node->mem_allocated = 0; @@ -1174,9 +1235,11 @@ palloc_extended(Size size, int flags) void pfree(void *pointer) { +#ifdef USE_VALGRIND MemoryContext context = GetMemoryChunkContext(pointer); +#endif - context->methods->free_p(context, pointer); + MCXT_METHOD(pointer, free_p) (pointer); VALGRIND_MEMPOOL_FREE(context, pointer); } @@ -1187,7 +1250,9 @@ pfree(void *pointer) void * repalloc(void *pointer, Size size) { +#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND) MemoryContext context = GetMemoryChunkContext(pointer); +#endif void *ret; if (!AllocSizeIsValid(size)) @@ -1198,15 +1263,17 @@ repalloc(void *pointer, Size size) /* isReset must be false already */ Assert(!context->isReset); - ret = context->methods->realloc(context, pointer, size); + ret = MCXT_METHOD(pointer, realloc) (pointer, size); if (unlikely(ret == NULL)) { + MemoryContext cxt = GetMemoryChunkContext(pointer); + MemoryContextStats(TopMemoryContext); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"), errdetail("Failed on request of size %zu in memory context \"%s\".", - size, context->name))); + size, cxt->name))); } VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size); @@ -1257,7 +1324,9 @@ MemoryContextAllocHuge(MemoryContext context, Size size) void * repalloc_huge(void *pointer, Size size) { +#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND) MemoryContext context = GetMemoryChunkContext(pointer); +#endif void *ret; if (!AllocHugeSizeIsValid(size)) @@ -1268,15 +1337,17 @@ repalloc_huge(void *pointer, Size size) /* isReset must be false already */ Assert(!context->isReset); - ret = context->methods->realloc(context, pointer, size); + ret = MCXT_METHOD(pointer, realloc) (pointer, size); if (unlikely(ret == NULL)) { + MemoryContext cxt = GetMemoryChunkContext(pointer); + MemoryContextStats(TopMemoryContext); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"), errdetail("Failed on request of size %zu in memory context \"%s\".", - size, context->name))); + size, cxt->name))); } VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size); diff --git a/src/backend/utils/mmgr/slab.c b/src/backend/utils/mmgr/slab.c index 67d97b22e5..e042e596f7 100644 --- a/src/backend/utils/mmgr/slab.c +++ b/src/backend/utils/mmgr/slab.c @@ -55,6 +55,8 @@ #include "lib/ilist.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" /* * SlabContext is a specialized implementation of MemoryContext. @@ -90,75 +92,23 @@ typedef struct SlabBlock dlist_node node; /* doubly-linked list */ int nfree; /* number of free chunks */ int firstFreeChunk; /* index of the first free chunk in the block */ -} SlabBlock; - -/* - * SlabChunk - * The prefix of each piece of memory in a SlabBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "slab" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). Since we support no machines on - * which MAXALIGN is more than twice sizeof(void *), this happens without any - * special hacking in this struct declaration. But there is a static - * assertion below that the alignment is done correctly. - */ -typedef struct SlabChunk -{ - SlabBlock *block; /* block owning this chunk */ SlabContext *slab; /* owning context */ - /* there must not be any padding to reach a MAXALIGN boundary here! */ -} SlabChunk; +} SlabBlock; +#define Slab_CHUNKHDRSZ sizeof(MemoryChunk) #define SlabPointerGetChunk(ptr) \ - ((SlabChunk *)(((char *)(ptr)) - sizeof(SlabChunk))) + ((MemoryChunk *)(((char *)(ptr)) - sizeof(MemoryChunk))) #define SlabChunkGetPointer(chk) \ - ((void *)(((char *)(chk)) + sizeof(SlabChunk))) + ((void *)(((char *)(chk)) + sizeof(MemoryChunk))) #define SlabBlockGetChunk(slab, block, idx) \ - ((SlabChunk *) ((char *) (block) + sizeof(SlabBlock) \ + ((MemoryChunk *) ((char *) (block) + sizeof(SlabBlock) \ + (idx * slab->fullChunkSize))) #define SlabBlockStart(block) \ ((char *) block + sizeof(SlabBlock)) #define SlabChunkIndex(slab, block, chunk) \ (((char *) chunk - SlabBlockStart(block)) / slab->fullChunkSize) -/* - * These functions implement the MemoryContext API for Slab contexts. - */ -static void *SlabAlloc(MemoryContext context, Size size); -static void SlabFree(MemoryContext context, void *pointer); -static void *SlabRealloc(MemoryContext context, void *pointer, Size size); -static void SlabReset(MemoryContext context); -static void SlabDelete(MemoryContext context); -static Size SlabGetChunkSpace(MemoryContext context, void *pointer); -static bool SlabIsEmpty(MemoryContext context); -static void SlabStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); -#ifdef MEMORY_CONTEXT_CHECKING -static void SlabCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for Slab contexts. - */ -static const MemoryContextMethods SlabMethods = { - SlabAlloc, - SlabFree, - SlabRealloc, - SlabReset, - SlabDelete, - SlabGetChunkSpace, - SlabIsEmpty, - SlabStats -#ifdef MEMORY_CONTEXT_CHECKING - ,SlabCheck -#endif -}; - - /* * SlabContextCreate * Create a new Slab context. @@ -168,8 +118,7 @@ static const MemoryContextMethods SlabMethods = { * blockSize: allocation block size * chunkSize: allocation chunk size * - * The chunkSize may not exceed: - * MAXALIGN_DOWN(SIZE_MAX) - MAXALIGN(sizeof(SlabBlock)) - sizeof(SlabChunk) + * The MAXALIGN(chunkSize) may not exceed MEMORYCHUNK_MAX_VALUE */ MemoryContext SlabContextCreate(MemoryContext parent, @@ -184,19 +133,14 @@ SlabContextCreate(MemoryContext parent, SlabContext *slab; int i; - /* Assert we padded SlabChunk properly */ - StaticAssertStmt(sizeof(SlabChunk) == MAXALIGN(sizeof(SlabChunk)), - "sizeof(SlabChunk) is not maxaligned"); - StaticAssertStmt(offsetof(SlabChunk, slab) + sizeof(MemoryContext) == - sizeof(SlabChunk), - "padding calculation in SlabChunk is wrong"); + Assert(MAXALIGN(chunkSize) <= MEMORYCHUNK_MAX_VALUE); /* Make sure the linked list node fits inside a freed chunk */ if (chunkSize < sizeof(int)) chunkSize = sizeof(int); /* chunk, including SLAB header (both addresses nicely aligned) */ - fullChunkSize = sizeof(SlabChunk) + MAXALIGN(chunkSize); + fullChunkSize = Slab_CHUNKHDRSZ + MAXALIGN(chunkSize); /* Make sure the block can store at least one chunk. */ if (blockSize < fullChunkSize + sizeof(SlabBlock)) @@ -265,7 +209,7 @@ SlabContextCreate(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) slab, T_SlabContext, - &SlabMethods, + MCTX_SLAB_ID, parent, name); @@ -279,7 +223,7 @@ SlabContextCreate(MemoryContext parent, * The code simply frees all the blocks in the context - we don't keep any * keeper blocks or anything like that. */ -static void +void SlabReset(MemoryContext context) { int i; @@ -322,7 +266,7 @@ SlabReset(MemoryContext context) * SlabDelete * Free all memory which is allocated in the given context. */ -static void +void SlabDelete(MemoryContext context) { /* Reset to release all the SlabBlocks */ @@ -336,12 +280,12 @@ SlabDelete(MemoryContext context) * Returns pointer to allocated memory of given size or NULL if * request could not be completed; memory is added to the slab. */ -static void * +void * SlabAlloc(MemoryContext context, Size size) { SlabContext *slab = castNode(SlabContext, context); SlabBlock *block; - SlabChunk *chunk; + MemoryChunk *chunk; int idx; Assert(slab); @@ -370,6 +314,7 @@ SlabAlloc(MemoryContext context, Size size) block->nfree = slab->chunksPerBlock; block->firstFreeChunk = 0; + block->slab = slab; /* * Put all the chunks on a freelist. Walk the chunks and point each @@ -378,7 +323,7 @@ SlabAlloc(MemoryContext context, Size size) for (idx = 0; idx < slab->chunksPerBlock; idx++) { chunk = SlabBlockGetChunk(slab, block, idx); - *(int32 *) SlabChunkGetPointer(chunk) = (idx + 1); + *(int32 *) MemoryChunkGetPointer(chunk) = (idx + 1); } /* @@ -426,8 +371,8 @@ SlabAlloc(MemoryContext context, Size size) * Remove the chunk from the freelist head. The index of the next free * chunk is stored in the chunk itself. */ - VALGRIND_MAKE_MEM_DEFINED(SlabChunkGetPointer(chunk), sizeof(int32)); - block->firstFreeChunk = *(int32 *) SlabChunkGetPointer(chunk); + VALGRIND_MAKE_MEM_DEFINED(MemoryChunkGetPointer(chunk), sizeof(int32)); + block->firstFreeChunk = *(int32 *) MemoryChunkGetPointer(chunk); Assert(block->firstFreeChunk >= 0); Assert(block->firstFreeChunk <= slab->chunksPerBlock); @@ -464,47 +409,47 @@ SlabAlloc(MemoryContext context, Size size) slab->minFreeChunks = 0; /* Prepare to initialize the chunk header. */ - VALGRIND_MAKE_MEM_UNDEFINED(chunk, sizeof(SlabChunk)); - - chunk->block = block; - chunk->slab = slab; + VALGRIND_MAKE_MEM_UNDEFINED(chunk, Slab_CHUNKHDRSZ); + MemoryChunkSetHdrMask(chunk, block, MAXALIGN(slab->chunkSize), + MCTX_SLAB_ID); #ifdef MEMORY_CONTEXT_CHECKING /* slab mark to catch clobber of "unused" space */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) { - set_sentinel(SlabChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); VALGRIND_MAKE_MEM_NOACCESS(((char *) chunk) + - sizeof(SlabChunk) + slab->chunkSize, + Slab_CHUNKHDRSZ + slab->chunkSize, slab->fullChunkSize - - (slab->chunkSize + sizeof(SlabChunk))); + (slab->chunkSize + Slab_CHUNKHDRSZ)); } #endif + #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) SlabChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif Assert(slab->nblocks * slab->blockSize == context->mem_allocated); - return SlabChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * SlabFree * Frees allocated memory; memory is removed from the slab. */ -static void -SlabFree(MemoryContext context, void *pointer) +void +SlabFree(void *pointer) { int idx; - SlabContext *slab = castNode(SlabContext, context); - SlabChunk *chunk = SlabPointerGetChunk(pointer); - SlabBlock *block = chunk->block; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) if (!sentinel_ok(pointer, slab->chunkSize)) elog(WARNING, "detected write past chunk end in %s %p", slab->header.name, chunk); @@ -560,13 +505,13 @@ SlabFree(MemoryContext context, void *pointer) { free(block); slab->nblocks--; - context->mem_allocated -= slab->blockSize; + slab->header.mem_allocated -= slab->blockSize; } else dlist_push_head(&slab->freelist[block->nfree], &block->node); Assert(slab->nblocks >= 0); - Assert(slab->nblocks * slab->blockSize == context->mem_allocated); + Assert(slab->nblocks * slab->blockSize == slab->header.mem_allocated); } /* @@ -582,13 +527,14 @@ SlabFree(MemoryContext context, void *pointer) * rather pointless - Slab is meant for chunks of constant size, and moreover * realloc is usually used to enlarge the chunk. */ -static void * -SlabRealloc(MemoryContext context, void *pointer, Size size) +void * +SlabRealloc(void *pointer, Size size) { - SlabContext *slab = castNode(SlabContext, context); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; Assert(slab); - /* can't do actual realloc with slab, but let's try to be gentle */ if (size == slab->chunkSize) return pointer; @@ -597,15 +543,33 @@ SlabRealloc(MemoryContext context, void *pointer, Size size) return NULL; /* keep compiler quiet */ } +/* + * SlabGetChunkContext + * Return the MemoryContext that 'pointer' belongs to. + */ +MemoryContext +SlabGetChunkContext(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; + + Assert(slab != NULL); + + return &slab->header; +} + /* * SlabGetChunkSpace * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -SlabGetChunkSpace(MemoryContext context, void *pointer) +Size +SlabGetChunkSpace(void *pointer) { - SlabContext *slab = castNode(SlabContext, context); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; Assert(slab); @@ -616,7 +580,7 @@ SlabGetChunkSpace(MemoryContext context, void *pointer) * SlabIsEmpty * Is an Slab empty of any allocated space? */ -static bool +bool SlabIsEmpty(MemoryContext context) { SlabContext *slab = castNode(SlabContext, context); @@ -635,7 +599,7 @@ SlabIsEmpty(MemoryContext context) * totals: if not NULL, add stats about this context into *totals. * print_to_stderr: print stats to stderr if true, elog otherwise. */ -static void +void SlabStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, @@ -697,7 +661,7 @@ SlabStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void SlabCheck(MemoryContext context) { int i; @@ -728,6 +692,11 @@ SlabCheck(MemoryContext context) elog(WARNING, "problem in slab %s: number of free chunks %d in block %p does not match freelist %d", name, block->nfree, block, i); + /* make sure the slab pointer correctly points to this context */ + if (block->slab != slab) + elog(WARNING, "problem in slab %s: bogus slab link in block %p", + name, block); + /* reset the bitmap of free chunks for this block */ memset(slab->freechunks, 0, (slab->chunksPerBlock * sizeof(bool))); idx = block->firstFreeChunk; @@ -742,7 +711,7 @@ SlabCheck(MemoryContext context) nfree = 0; while (idx < slab->chunksPerBlock) { - SlabChunk *chunk; + MemoryChunk *chunk; /* count the chunk as free, add it to the bitmap */ nfree++; @@ -750,8 +719,8 @@ SlabCheck(MemoryContext context) /* read index of the next free chunk */ chunk = SlabBlockGetChunk(slab, block, idx); - VALGRIND_MAKE_MEM_DEFINED(SlabChunkGetPointer(chunk), sizeof(int32)); - idx = *(int32 *) SlabChunkGetPointer(chunk); + VALGRIND_MAKE_MEM_DEFINED(MemoryChunkGetPointer(chunk), sizeof(int32)); + idx = *(int32 *) MemoryChunkGetPointer(chunk); } for (j = 0; j < slab->chunksPerBlock; j++) @@ -759,19 +728,19 @@ SlabCheck(MemoryContext context) /* non-zero bit in the bitmap means chunk the chunk is used */ if (!slab->freechunks[j]) { - SlabChunk *chunk = SlabBlockGetChunk(slab, block, j); - - /* chunks have both block and slab pointers, so check both */ - if (chunk->block != block) + MemoryChunk *chunk = SlabBlockGetChunk(slab, block, j); + SlabBlock *chunkblock = (SlabBlock *) MemoryChunkGetBlock(chunk); + + /* + * check the chunk's blockoffset correctly points back to + * the block + */ + if (chunkblock != block) elog(WARNING, "problem in slab %s: bogus block link in block %p, chunk %p", name, block, chunk); - if (chunk->slab != slab) - elog(WARNING, "problem in slab %s: bogus slab link in block %p, chunk %p", - name, block, chunk); - /* there might be sentinel (thanks to alignment) */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) if (!sentinel_ok(chunk, slab->chunkSize)) elog(WARNING, "problem in slab %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); diff --git a/src/include/nodes/memnodes.h b/src/include/nodes/memnodes.h index 16cd56da6d..63d07358cd 100644 --- a/src/include/nodes/memnodes.h +++ b/src/include/nodes/memnodes.h @@ -59,11 +59,12 @@ typedef struct MemoryContextMethods { void *(*alloc) (MemoryContext context, Size size); /* call this free_p in case someone #define's free() */ - void (*free_p) (MemoryContext context, void *pointer); - void *(*realloc) (MemoryContext context, void *pointer, Size size); + void (*free_p) (void *pointer); + void *(*realloc) (void *pointer, Size size); void (*reset) (MemoryContext context); void (*delete_context) (MemoryContext context); - Size (*get_chunk_space) (MemoryContext context, void *pointer); + MemoryContext (*get_chunk_context) (void *pointer); + Size (*get_chunk_space) (void *pointer); bool (*is_empty) (MemoryContext context); void (*stats) (MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, diff --git a/src/include/utils/memutils.h b/src/include/utils/memutils.h index 495d1af201..52bc41ec53 100644 --- a/src/include/utils/memutils.h +++ b/src/include/utils/memutils.h @@ -41,8 +41,11 @@ #define AllocSizeIsValid(size) ((Size) (size) <= MaxAllocSize) +/* Must be less than SIZE_MAX */ #define MaxAllocHugeSize (SIZE_MAX / 2) +#define InvalidAllocSize SIZE_MAX + #define AllocHugeSizeIsValid(size) ((Size) (size) <= MaxAllocHugeSize) @@ -79,6 +82,7 @@ extern void MemoryContextDeleteChildren(MemoryContext context); extern void MemoryContextSetIdentifier(MemoryContext context, const char *id); extern void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent); +extern MemoryContext GetMemoryChunkContext(void *pointer); extern Size GetMemoryChunkSpace(void *pointer); extern MemoryContext MemoryContextGetParent(MemoryContext context); extern bool MemoryContextIsEmpty(MemoryContext context); @@ -98,53 +102,6 @@ extern bool MemoryContextContains(MemoryContext context, void *pointer); #define MemoryContextCopyAndSetIdentifier(cxt, id) \ MemoryContextSetIdentifier(cxt, MemoryContextStrdup(cxt, id)) -/* - * GetMemoryChunkContext - * Given a currently-allocated chunk, determine the context - * it belongs to. - * - * All chunks allocated by any memory context manager are required to be - * preceded by the corresponding MemoryContext stored, without padding, in the - * preceding sizeof(void*) bytes. A currently-allocated chunk must contain a - * backpointer to its owning context. The backpointer is used by pfree() and - * repalloc() to find the context to call. - */ -#ifndef FRONTEND -static inline MemoryContext -GetMemoryChunkContext(void *pointer) -{ - MemoryContext context; - - /* - * Try to detect bogus pointers handed to us, poorly though we can. - * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an - * allocated chunk. - */ - Assert(pointer != NULL); - Assert(pointer == (void *) MAXALIGN(pointer)); - - /* - * OK, it's probably safe to look at the context. - */ - context = *(MemoryContext *) (((char *) pointer) - sizeof(void *)); - - AssertArg(MemoryContextIsValid(context)); - - return context; -} -#endif - -/* - * This routine handles the context-type-independent part of memory - * context creation. It's intended to be called from context-type- - * specific creation routines, and noplace else. - */ -extern void MemoryContextCreate(MemoryContext node, - NodeTag tag, - const MemoryContextMethods *methods, - MemoryContext parent, - const char *name); - extern void HandleLogMemoryContextInterrupt(void); extern void ProcessLogMemoryContextInterrupt(void); diff --git a/src/include/utils/memutils_internal.h b/src/include/utils/memutils_internal.h new file mode 100644 index 0000000000..e10a559726 --- /dev/null +++ b/src/include/utils/memutils_internal.h @@ -0,0 +1,130 @@ +/*------------------------------------------------------------------------- + * + * memutils_internal.h + * This file contains declarations for memory allocation utility + * functions for internal use. + * + * + * Portions Copyright (c) 2022, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/utils/memutils_internal.h + * + *------------------------------------------------------------------------- + */ + +#ifndef MEMUTILS_INTERNAL_H +#define MEMUTILS_INTERNAL_H + +#include "utils/memutils.h" + +extern void *AllocSetAlloc(MemoryContext context, Size size); +extern void AllocSetFree(void *pointer); +extern void *AllocSetRealloc(void *pointer, Size size); +extern void AllocSetReset(MemoryContext context); +extern void AllocSetDelete(MemoryContext context); +extern MemoryContext AllocSetGetChunkContext(void *pointer); +extern Size AllocSetGetChunkSpace(void *pointer); +extern bool AllocSetIsEmpty(MemoryContext context); +extern void AllocSetStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); + +#ifdef MEMORY_CONTEXT_CHECKING +extern void AllocSetCheck(MemoryContext context); +#endif + + +extern void *GenerationAlloc(MemoryContext context, Size size); +extern void GenerationFree(void *pointer); +extern void *GenerationRealloc(void *pointer, Size size); +extern void GenerationReset(MemoryContext context); +extern void GenerationDelete(MemoryContext context); +extern MemoryContext GenerationGetChunkContext(void *pointer); +extern Size GenerationGetChunkSpace(void *pointer); +extern bool GenerationIsEmpty(MemoryContext context); +extern void GenerationStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); + +#ifdef MEMORY_CONTEXT_CHECKING +extern void GenerationCheck(MemoryContext context); +#endif + + +/* + * These functions implement the MemoryContext API for Slab contexts. + */ +extern void *SlabAlloc(MemoryContext context, Size size); +extern void SlabFree(void *pointer); +extern void *SlabRealloc(void *pointer, Size size); +extern void SlabReset(MemoryContext context); +extern void SlabDelete(MemoryContext context); +extern MemoryContext SlabGetChunkContext(void *pointer); +extern Size SlabGetChunkSpace(void *pointer); +extern bool SlabIsEmpty(MemoryContext context); +extern void SlabStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); +#ifdef MEMORY_CONTEXT_CHECKING +extern void SlabCheck(MemoryContext context); +#endif + +/* + * MemoryContextMethodID + * A unique identifier for each MemoryContext implementation which + * indicates the index into the mcxt_methods[] array. See mcxt.c. + */ +typedef enum MemoryContextMethodID +{ + MCTX_ASET_ID, + MCTX_GENERATION_ID, + MCTX_SLAB_ID, +} MemoryContextMethodID; + +/* + * The number of bits that 8-byte memory chunk headers can use to encode the + * MemoryContextMethodID. + */ +#define MEMORY_CONTEXT_METHODID_BITS 3 +/* + * The maximum possible value of for a MemoryContextMethodID and the bitmask + * for binary ANDing out unrelated bits in the 8-byte chunk header. This must + * be set to the maximum value that can be represented by + * MEMORY_CONTEXT_METHODID_BITS bits. + */ +#define MEMORY_CONTEXT_METHODID_MASK 7 + +/* + * This routine handles the context-type-independent part of memory + * context creation. It's intended to be called from context-type- + * specific creation routines, and noplace else. + */ +extern void MemoryContextCreate(MemoryContext node, + NodeTag tag, + MemoryContextMethodID method_id, + MemoryContext parent, + const char *name); + +static inline MemoryContextMethodID +GetMemoryChunkMethodID(void *pointer) +{ + uint64 header; + + /* + * Try to detect bogus pointers handed to us, poorly though we can. + * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an + * allocated chunk. + */ + Assert(pointer != NULL); + Assert(pointer == (void *) MAXALIGN(pointer)); + + header = *((uint64 *) ((char *) pointer - sizeof(uint64))); + + return header & MEMORY_CONTEXT_METHODID_MASK; +} + +#endif /* MEMUTILS_INTERNAL_H */ diff --git a/src/include/utils/memutils_memorychunk.h b/src/include/utils/memutils_memorychunk.h new file mode 100644 index 0000000000..3897dfd508 --- /dev/null +++ b/src/include/utils/memutils_memorychunk.h @@ -0,0 +1,231 @@ +/*------------------------------------------------------------------------- + * + * memutils_memorychunk.h + * Here we define a struct named MemoryChunk which implementations of + * MemoryContexts may use as a header for chunks of memory they allocate. + * + * A MemoryChunk provides a lightweight header which a MemoryContext can use + * to store a reference back to the block the which the given chunk is + * allocated on and also an additional 30-bits to store another value such as + * the size of the allocated chunk. + * + * Although MemoryChunks are used by each of our MemoryContexts, future + * implementations may choose to implement their own method for storing chunk + * headers. The only requirement is that the header end with an 8-byte value + * which the least significant 3-bits of are set to the MemoryContextMethodID + * of the given context. + * + * By default, a MemoryChunk is 8 bytes in size, however when + * MEMORY_CONTEXT_CHECKING is defined the header becomes 16 bytes in size due + * to the additional requested_size field. The MemoryContext may use this + * field for whatever they wish, but it is intended to be used for additional + * checks which are only done in MEMORY_CONTEXT_CHECKING builds. + * + * The MemoryChunk contains a uint64 field named 'hdrmask'. This field is + * used to encode 4 separate pieces of information. Starting with the least + * significant bits of 'hdrmask', the bit space is reserved as follows: + * + * 1. 3-bits to indicate the MemoryContextMethodID as defined by + * MEMORY_CONTEXT_METHODID_MASK + * 2. 1-bit to denote an "external" chunk (see below) + * 3. 30-bits reserved for the MemoryContext to use for anything it + * requires. Most MemoryContext likely want to store the size of the + * chunk here. + * 4. 30-bits for the number of bytes that must be subtracted from the chunk + * to obtain the address of the block that the chunk is stored on. + * + * In some cases, for example when memory allocations become large, it's + * possible fields 3 and 4 above are not large enough to store the values + * required for the chunk. In this case, the MemoryContext can choose to mark + * the chunk as "external" by calling the MemoryChunkSetExternal() function. + * When this is done, fields 3 and 4 are unavailable for use by the + * MemoryContext and it's up to the MemoryContext itself to devise its own + * method for getting the reference to the block. + * + * Interface: + * + * MemoryChunkSetHdrMask: + * Used to set up a non-external MemoryChunk. + * + * MemoryChunkSetHdrMaskExternal: + * Used to set up an externally managed MemoryChunk. + * + * MemoryChunkIsExternal: + * Determine if the given MemoryChunk is externally managed, i.e. + * MemoryChunkSetHdrMaskExternal() was called on the chunk. + * + * MemoryChunkGetValue: + * For non-external chunks, return the stored 30-bit value as it was set + * in the call to MemoryChunkSetHdrMask(). + * + * MemoryChunkGetBlock: + * For non-external chunks, return a pointer to the block as it was set + * in the call to MemoryChunkSetHdrMask(). + * + * Also exports: + * MEMORYCHUNK_MAX_VALUE + * MEMORYCHUNK_MAX_BLOCKOFFSET + * PointerGetMemoryChunk + * MemoryChunkGetPointer + * + * Portions Copyright (c) 2022, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/utils/memutils_memorychunk.h + * + *------------------------------------------------------------------------- + */ + +#ifndef MEMUTILS_MEMORYCHUNK_H +#define MEMUTILS_MEMORYCHUNK_H + +#include "utils/memutils_internal.h" + + /* + * The maximum allowed value that MemoryContexts can store in the value + * field. Must be 1 less than a power of 2. + */ +#define MEMORYCHUNK_MAX_VALUE 0x3FFFFFFF + +/* + * The maximum distance in bytes that a MemoryChunk can be offset from the + * block that is storing the chunk. Must be 1 less than a power of 2. + */ +#define MEMORYCHUNK_MAX_BLOCKOFFSET 0x3FFFFFFF + +/* define the least significant base-0 bit of each portion of the hdrmask */ +#define MEMORYCHUNK_EXTERNAL_BASEBIT MEMORY_CONTEXT_METHODID_BITS +#define MEMORYCHUNK_VALUE_BASEBIT (MEMORYCHUNK_EXTERNAL_BASEBIT + 1) +#define MEMORYCHUNK_BLOCKOFFSET_BASEBIT (MEMORYCHUNK_VALUE_BASEBIT + 30) + +/* A magic number for storing in the free bits of an external chunk */ +#define MEMORYCHUNK_MAGIC (UINT64CONST(0xB1A8DB858EB6EFBA) >> \ + MEMORYCHUNK_VALUE_BASEBIT << \ + MEMORYCHUNK_VALUE_BASEBIT) + +typedef struct MemoryChunk +{ +#ifdef MEMORY_CONTEXT_CHECKING + Size requested_size; +#endif + + /* bitfield for storing details about the chunk */ + uint64 hdrmask; /* must be last */ +} MemoryChunk; + +/* Get the MemoryChunk from the pointer */ +#define PointerGetMemoryChunk(p) ((MemoryChunk *) ((char *) (p) - sizeof(MemoryChunk))) +/* Get the pointer from the MemoryChunk */ +#define MemoryChunkGetPointer(c) ((void *) ((char *) (c) + sizeof(MemoryChunk))) + +/* private macros for making the inline functions below more simple */ +#define HdrMaskIsExternal(hdrmask) \ + ((hdrmask) & (1 << MEMORYCHUNK_EXTERNAL_BASEBIT)) +#define HdrMaskGetValue(hdrmask) \ + (((hdrmask) >> MEMORYCHUNK_VALUE_BASEBIT) & MEMORYCHUNK_MAX_VALUE) + +/* + * We should have used up all the bits here, so the compiler is likely to + * optimize out the & MEMORYCHUNK_MAX_BLOCKOFFSET. + */ +#define HdrMaskBlockOffset(hdrmask) \ + (((hdrmask) >> MEMORYCHUNK_BLOCKOFFSET_BASEBIT) & MEMORYCHUNK_MAX_BLOCKOFFSET) + +/* For external chunks only, check the magic number matches */ +#define HdrMaskCheckMagic(hdrmask) \ + (MEMORYCHUNK_MAGIC == \ + ((hdrmask) >> MEMORYCHUNK_VALUE_BASEBIT << MEMORYCHUNK_VALUE_BASEBIT)) +/* + * MemoryChunkSetHdrMask + * Store the given 'block', 'chunk_size' and 'methodid' in the given + * MemoryChunk. + * + * The number of bytes between 'block' and 'chunk' must be <= + * MEMORYCHUNK_MAX_BLOCKOFFSET. + * 'value' must be <= MEMORYCHUNK_MAX_VALUE. + */ +static inline void +MemoryChunkSetHdrMask(MemoryChunk *chunk, void *block, + Size value, MemoryContextMethodID methodid) +{ + Size blockoffset = (char *) chunk - (char *) block; + + Assert((char *) chunk > (char *) block); + Assert(blockoffset <= MEMORYCHUNK_MAX_BLOCKOFFSET); + Assert(value <= MEMORYCHUNK_MAX_VALUE); + Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK); + + chunk->hdrmask = (blockoffset << MEMORYCHUNK_BLOCKOFFSET_BASEBIT) | + (value << MEMORYCHUNK_VALUE_BASEBIT) | + methodid; +} + +/* + * MemoryChunkSetHdrMaskExternal + * Set 'chunk' as an externally managed chunk. Here we only record the + * MemoryContextMethodID and set the external chunk bit. + */ +static inline void +MemoryChunkSetHdrMaskExternal(MemoryChunk *chunk, + MemoryContextMethodID methodid) +{ + Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK); + + chunk->hdrmask = MEMORYCHUNK_MAGIC | (1 << MEMORYCHUNK_EXTERNAL_BASEBIT) | + methodid; +} + +/* + * MemoryChunkIsExternal + * Return true if 'chunk' is marked as external. + */ +static inline bool +MemoryChunkIsExternal(MemoryChunk *chunk) +{ + /* + * External chunks should always store MEMORYCHUNK_MAGIC in the upper + * portion of the hdrmask. + */ + Assert(!HdrMaskIsExternal(chunk->hdrmask) || + HdrMaskCheckMagic(chunk->hdrmask)); + + return HdrMaskIsExternal(chunk->hdrmask); +} + +/* + * MemoryChunkGetValue + * For non-external chunks, returns the value field as it was set in + * MemoryChunkSetHdrMask. + */ +static inline Size +MemoryChunkGetValue(MemoryChunk *chunk) +{ + Assert(!HdrMaskIsExternal(chunk->hdrmask)); + + return HdrMaskGetValue(chunk->hdrmask); +} + +/* + * MemoryChunkGetBlock + * For non-external chunks, returns the pointer to the block as was set + * in MemoryChunkSetHdrMask. + */ +static inline void * +MemoryChunkGetBlock(MemoryChunk *chunk) +{ + Assert(!HdrMaskIsExternal(chunk->hdrmask)); + + return (void *) ((char *) chunk - HdrMaskBlockOffset(chunk->hdrmask)); +} + +/* cleanup all internal definitions */ +#undef MEMORYCHUNK_EXTERNAL_BASEBIT +#undef MEMORYCHUNK_VALUE_BASEBIT +#undef MEMORYCHUNK_BLOCKOFFSET_BASEBIT +#undef MEMORYCHUNK_MAGIC +#undef HdrMaskIsExternal +#undef HdrMaskGetValue +#undef HdrMaskBlockOffset +#undef HdrMaskCheckMagic + +#endif /* MEMUTILS_MEMORYCHUNK_H */ diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 35c9f1efce..86057fd1ba 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -57,6 +57,7 @@ AlenState Alias AllocBlock AllocChunk +AllocFreelistLink AllocPointer AllocSet AllocSetContext @@ -1521,12 +1522,14 @@ MemoizeKey MemoizePath MemoizeState MemoizeTuple +MemoryChunk MemoryContext MemoryContextCallback MemoryContextCallbackFunction MemoryContextCounters MemoryContextData MemoryContextMethods +MemoryContextMethodID MemoryStatsPrintFunc MergeAction MergeActionState -- 2.35.1.windows.2
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-26 05:16  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-08-26 05:16 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 23 Aug 2022 at 21:03, David Rowley <dgrowleyml@gmail.com> wrote:
> Finally, the v5 patch with the fixes mentioned above.

The CFbot just alerted me to the cplusplus check was failing with the
v5 patch, so here's v6.

> I'm pretty keen to get this patch committed early next week.  This is
> quite core infrastructure, so it would be good if the patch gets a few
> extra eyeballs on it before then.

That'll probably be New Zealand Monday, unless objects before then.

David

Attachments:

v6-0001-Improve-performance-of-and-reduce-overheads-of-me.patch (text/plain, 104.3K) download From 41419082028216112c92f9ff5bdec21f952b7f37 Mon Sep 17 00:00:00 2001 From: David Rowley <dgrowley@gmail.com> Date: Thu, 9 Jun 2022 20:09:22 +1200 Subject: [PATCH v6] Improve performance of and reduce overheads of memory management Whenever we palloc a chunk of memory, traditionally, we prefix the returned pointer with a pointer to the memory context to which the chunk belongs. This is required so that we're able to easily determine the owning context when performing operations such as pfree() and repalloc(). For the AllocSet context, prior to this commit we additionally prefixed the pointer to the owning context with the size of the chunk. This made the header 16 bytes in size. This 16-byte overhead was required for all AllocSet allocations regardless of the allocation size. For the generation context, the problem was worse; in addition to the pointer to the owning context and chunk size, we also stored a pointer to the owning block so that we could track the number of freed chunks on a block. The slab allocator had a 16-byte chunk header. The changes being made here reduce the chunk header size down to just 8 bytes for all 3 of our memory context types. For small to medium sized allocations, this significantly increases the number of chunks that we can fit on a given block which results in much more efficient use of memory. Additionally, this commit completely changes the rule that pointers to palloc'd memory must be directly prefixed by a pointer to the owning memory context and instead, we now insist that they're directly prefixed by an 8-byte value where the least significant 3-bits are set to a value to indicate which type of memory context the pointer belongs to. Using those 3 bits as an index (known as MemoryContextMethodID) to a new array which stores the methods for each memory context type, we're now able to pass the pointer given to functions such as pfree() and repalloc() to the function specific to that context implementation to allow them to devise their own methods of finding the memory context which owns the given allocated chunk of memory. The reason we're able to reduce the chunk header down to just 8 bytes is because of the way we make use of the remaining 61 bits of the required 8-byte chunk header. Here we also implement a general-purpose MemoryChunk struct which makes use of those 61 remaining bits to allow the storage of a 30-bit value which the MemoryContext is free to use as it pleases, and also the number of bytes which must be subtracted from the chunk to get a reference to the block that the chunk is stored on (also 30 bits). The 1 additional remaining bit is to denote if the chunk is an "external" chunk or not. External here means that the chunk header does not store the 30-bit value or the block offset. The MemoryContext can use these external chunks at any time, but must use them if any of the two 30-bit fields are not large enough for the value(s) that need to be stored in them. When the chunk is marked as external, it is up to the MemoryContext to devise its own means to determine the block offset. Using 3-bits for the MemoryContextMethodID does mean we're limiting ourselves to only having a maximum of 8 different memory context types. We could reduce the bit space for the 30-bit value a little to make way for more than 3 bits, but it seems like it might be better to do that only if we ever need more than 8 context types. This would only be a problem if some future memory context type which does not use MemoryChunk really couldn't give up any of the 61 remaining bits in the chunk header. With this MemoryChunk, each of our 3 memory context types can quickly obtain a reference to the block any given chunk is located on. AllocSet is able to find the context to which the chunk is owned by first obtaining a reference to the block by subtracting the block offset as is stored in the 'hdrmask' field and then referencing the block's 'aset' field. The Generation context uses the same method, but GenerationBlock did not have a field pointing back to the owning context, so one is added by this commit. In aset.c and generation.c, all allocations larger than allocChunkLimit are stored on dedicated blocks. When there's just a single chunk on a block like this, it's easy to find the block from the chunk, we just subtract the size of the block header from the chunk pointer. The size of these chunks is also known as we store the endptr on the block, so we can just subtract the pointer to the allocated memory from that. Because we can easily find the owning block and the size of the chunk for these dedicated blocks, we just always use external chunks for allocation sizes larger than allocChunkLimit. For geneartion.c, this sidesteps the problem of non-external MemoryChunks being unable to represent chunk sizes >= 1GB. This is less of a problem for aset.c as we store the freelist index in the MemoryChunk's spare 30-bit field. we can easily reverse engineer the chunk size from this when needed. Storing this saves AllocSetFree() from having to make a call to AllocSetFreeIndex() to determine which freelist to put the newly freed chunk on. For the slab allocator, this commit adds a new restriction that slab chunks cannot be >= 1GB in size. If there happened to be any users of slab.c which used chunk sizes this large, they really should be using AllocSet instead. Here we also add a restriction that normal non-dedicated blocks cannot be 1GB or larger. It's now not possible to pass a 'maxBlockSize' >= 1GB during the creation of an AllocSet or Generation context. Allocations can still be larger than 1GB, it's just these will always be on dedicated blocks (which are not restricted to 1GB in size). Author: Andres Freund, David Rowley Discussion: https://postgr.es/m/CAApHDvpjauCRXcgcaL6+e3eqecEHoeRm9D-kcbuvBitgPnW=vw@mail.gmail.com --- src/backend/utils/mmgr/README | 60 ++- src/backend/utils/mmgr/aset.c | 506 ++++++++++++----------- src/backend/utils/mmgr/generation.c | 350 ++++++++-------- src/backend/utils/mmgr/mcxt.c | 91 +++- src/backend/utils/mmgr/slab.c | 197 ++++----- src/include/nodes/memnodes.h | 7 +- src/include/utils/memutils.h | 51 +-- src/include/utils/memutils_internal.h | 130 ++++++ src/include/utils/memutils_memorychunk.h | 231 +++++++++++ src/tools/pgindent/typedefs.list | 3 + 10 files changed, 1032 insertions(+), 594 deletions(-) create mode 100644 src/include/utils/memutils_internal.h create mode 100644 src/include/utils/memutils_memorychunk.h diff --git a/src/backend/utils/mmgr/README b/src/backend/utils/mmgr/README index 221b4bd343..c94194f7d3 100644 --- a/src/backend/utils/mmgr/README +++ b/src/backend/utils/mmgr/README @@ -378,35 +378,55 @@ MemoryContext like the parent and child contexts, and the name of the context. This is essentially an abstract superclass, and the behavior is -determined by the "methods" pointer is its virtual function table -(struct MemoryContextMethods). Specific memory context types will use -derived structs having these fields as their first fields. All the +determined by the "methods" pointer which references which set of +MemoryContextMethods are to be used. Specific memory context types will +use derived structs having these fields as their first fields. All the contexts of a specific type will have methods pointers that point to -the same static table of function pointers. +the corresponding element in the mcxt_methods[] array as defined in mcxt.c. While operations like allocating from and resetting a context take the relevant MemoryContext as a parameter, operations like free and realloc are trickier. To make those work, we require all memory context types to produce allocated chunks that are immediately, -without any padding, preceded by a pointer to the corresponding -MemoryContext. +without any padding, preceded by a uint64 value of which the least +significant 3 bits are set to the owning context's MemoryContextMethodID. +This allows the code to determine the correct MemoryContextMethods to +use by looking up the mcxt_methods[] array using the 3 bits as an index +into that array. If a type of allocator needs additional information about its chunks, like e.g. the size of the allocation, that information can in turn -precede the MemoryContext. This means the only overhead implied by -the memory context mechanism is a pointer to its context, so we're not -constraining context-type designers very much. - -Given this, routines like pfree determine their corresponding context -with an operation like (although that is usually encapsulated in -GetMemoryChunkContext()) - - MemoryContext context = *(MemoryContext*) (((char *) pointer) - sizeof(void *)); - -and then invoke the corresponding method for the context - - context->methods->free_p(pointer); - +either be encoded into the remaining 61 bits of the preceding uint64 value +or if more space is required, additional values may be stored directly prior +to the uint64 value. It is up to the context implementation to manage this. + +Given this, routines like pfree can determine which set of +MemoryContextMethods to call the free_p function for by calling +GetMemoryChunkMethodID() and finding the corresponding MemoryContextMethods +in the mcxt_methods array[]. For convenience, the MCXT_METHOD() macro is +provided, making the code as simple as: + +void +pfree(void *pointer) +{ + MCXT_METHOD(pointer, free_p)(pointer); +} + +All of the current memory contexts make use of the MemoryChunk header type +which is defined in memutils_memorychunk.h. This suits all of the existing +context types well as it makes use of the remaining 61-bits of the uint64 +header to efficiently encode the size of the chunk of memory (or freelist +index, in the case of aset.c) and the number of bytes which must be subtracted +from the chunk in order to obtain a reference to the block that the chunk +belongs to. 30 bits are used for each of these. If more than 30 bits are +required then the memory context must manage that itself. This can be done by +calling the MemoryChunkSetHdrMaskExternal() function on the given chunk. +Currently, each memory context type stores large allocations on dedicated +blocks (which always contain only a single chunk). For these, finding the +block is simple as we know that the chunk must be the first on the given +block, so the block is always at a fixed offset to the chunk. For these, +finding the size of the chunk is also simple as the block always stores an +endptr which we can use to calculate the size of the chunk. More Control Over aset.c Behavior --------------------------------- diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index ec3e264a73..a4b4e2ea45 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -49,6 +49,8 @@ #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" /*-------------------- * Chunk freelist k holds chunks of size 1 << (k + ALLOC_MINBITS), @@ -66,7 +68,9 @@ * CAUTION: ALLOC_MINBITS must be large enough so that * 1<<ALLOC_MINBITS is at least MAXALIGN, * or we may fail to align the smallest chunks adequately. - * 8-byte alignment is enough on all currently known machines. + * 8-byte alignment is enough on all currently known machines. This 8-byte + * minimum also allows us to store a pointer to the next freelist item within + * the chunk of memory itself. * * With the current parameters, request sizes up to 8K are treated as chunks, * larger requests go into dedicated blocks. Change ALLOCSET_NUM_FREELISTS @@ -98,10 +102,9 @@ */ #define ALLOC_BLOCKHDRSZ MAXALIGN(sizeof(AllocBlockData)) -#define ALLOC_CHUNKHDRSZ sizeof(struct AllocChunkData) +#define ALLOC_CHUNKHDRSZ sizeof(MemoryChunk) typedef struct AllocBlockData *AllocBlock; /* forward reference */ -typedef struct AllocChunkData *AllocChunk; /* * AllocPointer @@ -109,6 +112,33 @@ typedef struct AllocChunkData *AllocChunk; */ typedef void *AllocPointer; +/* + * AllocFreelistLink + * When pfreeing memory, if we maintain a freelist for the given chunk's + * size then we use a AllocFreelistLink to point to the current item in + * the AllocSetContext's freelist and then set the given freelist element + * to point to the chunk being freed. + */ +typedef struct AllocFreelistLink +{ + MemoryChunk *next; +} AllocFreelistLink; + +/* + * Obtain a AllocFreelistLink for the given chunk. Allocation sizes are + * always at least sizeof(AllocFreelistLink), so we reuse the pointer's memory + * itself to store the freelist link. To make it less likely that any write + * after pfree() bugs corrupt this, we put the link at the very end of the + * allocated chunk. + */ +#define GetFreeListLink(chkptr, chksz) \ + (AllocFreelistLink *) ((char *) (chkptr) + ALLOC_CHUNKHDRSZ + \ + (chksz) - sizeof(AllocFreelistLink)) + +/* Determine the size of the chunk based on the freelist index */ +#define GetChunkSizeFromFreelistIdx(fidx) \ + ((((Size) 1) << ALLOC_MINBITS) << (fidx)) + /* * AllocSetContext is our standard implementation of MemoryContext. * @@ -123,7 +153,7 @@ typedef struct AllocSetContext MemoryContextData header; /* Standard memory-context fields */ /* Info about storage allocated in this context: */ AllocBlock blocks; /* head of list of blocks in this set */ - AllocChunk freelist[ALLOCSET_NUM_FREELISTS]; /* free chunk lists */ + MemoryChunk *freelist[ALLOCSET_NUM_FREELISTS]; /* free chunk lists */ /* Allocation parameters for this context: */ Size initBlockSize; /* initial block size */ Size maxBlockSize; /* maximum block size */ @@ -139,8 +169,8 @@ typedef AllocSetContext *AllocSet; /* * AllocBlock * An AllocBlock is the unit of memory that is obtained by aset.c - * from malloc(). It contains one or more AllocChunks, which are - * the units requested by palloc() and freed by pfree(). AllocChunks + * from malloc(). It contains one or more MemoryChunks, which are + * the units requested by palloc() and freed by pfree(). MemoryChunks * cannot be returned to malloc() individually, instead they are put * on freelists by pfree() and re-used by the next palloc() that has * a matching request size. @@ -158,48 +188,12 @@ typedef struct AllocBlockData } AllocBlockData; /* - * AllocChunk - * The prefix of each piece of memory in an AllocBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "aset" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). We simplify matters for this - * module by requiring sizeof(AllocChunkData) to be maxaligned, and then - * we can ensure things work by adding any required alignment padding before - * the "aset" field. There is a static assertion below that the alignment - * is done correctly. - */ -typedef struct AllocChunkData -{ - /* size is always the size of the usable space in the chunk */ - Size size; -#ifdef MEMORY_CONTEXT_CHECKING - /* when debugging memory usage, also store actual requested size */ - /* this is zero in a free chunk */ - Size requested_size; - -#define ALLOCCHUNK_RAWSIZE (SIZEOF_SIZE_T * 2 + SIZEOF_VOID_P) -#else -#define ALLOCCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P) -#endif /* MEMORY_CONTEXT_CHECKING */ - - /* ensure proper alignment by adding padding if needed */ -#if (ALLOCCHUNK_RAWSIZE % MAXIMUM_ALIGNOF) != 0 - char padding[MAXIMUM_ALIGNOF - ALLOCCHUNK_RAWSIZE % MAXIMUM_ALIGNOF]; -#endif - - /* aset is the owning aset if allocated, or the freelist link if free */ - void *aset; - /* there must not be any padding to reach a MAXALIGN boundary here! */ -} AllocChunkData; - -/* - * Only the "aset" field should be accessed outside this module. + * Only the "hdrmask" field should be accessed outside this module. * We keep the rest of an allocated chunk's header marked NOACCESS when using * valgrind. But note that chunk headers that are in a freelist are kept * accessible, for simplicity. */ -#define ALLOCCHUNK_PRIVATE_LEN offsetof(AllocChunkData, aset) +#define ALLOCCHUNK_PRIVATE_LEN offsetof(MemoryChunk, hdrmask) /* * AllocPointerIsValid @@ -213,10 +207,12 @@ typedef struct AllocChunkData */ #define AllocSetIsValid(set) PointerIsValid(set) -#define AllocPointerGetChunk(ptr) \ - ((AllocChunk)(((char *)(ptr)) - ALLOC_CHUNKHDRSZ)) -#define AllocChunkGetPointer(chk) \ - ((AllocPointer)(((char *)(chk)) + ALLOC_CHUNKHDRSZ)) +/* + * We always store external chunks on a dedicated block. This makes fetching + * the block from an external chunk easy since it's always the first and only + * chunk on the block. + */ +#define ExternalChunkGetBlock(chunk) (AllocBlock) ((char *) chunk - ALLOC_BLOCKHDRSZ) /* * Rather than repeatedly creating and deleting memory contexts, we keep some @@ -260,42 +256,6 @@ static AllocSetFreeList context_freelists[2] = } }; -/* - * These functions implement the MemoryContext API for AllocSet contexts. - */ -static void *AllocSetAlloc(MemoryContext context, Size size); -static void AllocSetFree(MemoryContext context, void *pointer); -static void *AllocSetRealloc(MemoryContext context, void *pointer, Size size); -static void AllocSetReset(MemoryContext context); -static void AllocSetDelete(MemoryContext context); -static Size AllocSetGetChunkSpace(MemoryContext context, void *pointer); -static bool AllocSetIsEmpty(MemoryContext context); -static void AllocSetStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); - -#ifdef MEMORY_CONTEXT_CHECKING -static void AllocSetCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for AllocSet contexts. - */ -static const MemoryContextMethods AllocSetMethods = { - AllocSetAlloc, - AllocSetFree, - AllocSetRealloc, - AllocSetReset, - AllocSetDelete, - AllocSetGetChunkSpace, - AllocSetIsEmpty, - AllocSetStats -#ifdef MEMORY_CONTEXT_CHECKING - ,AllocSetCheck -#endif -}; - /* ---------- * AllocSetFreeIndex - @@ -387,18 +347,24 @@ AllocSetContextCreateInternal(MemoryContext parent, AllocSet set; AllocBlock block; - /* Assert we padded AllocChunkData properly */ + /* ensure MemoryChunk's size is properly maxaligned */ StaticAssertStmt(ALLOC_CHUNKHDRSZ == MAXALIGN(ALLOC_CHUNKHDRSZ), - "sizeof(AllocChunkData) is not maxaligned"); - StaticAssertStmt(offsetof(AllocChunkData, aset) + sizeof(MemoryContext) == - ALLOC_CHUNKHDRSZ, - "padding calculation in AllocChunkData is wrong"); + "sizeof(MemoryChunk) is not maxaligned"); + /* check we have enough space to store the freelist link */ + StaticAssertStmt(sizeof(AllocFreelistLink) <= (1 << ALLOC_MINBITS), + "sizeof(AllocFreelistLink) larger than minimum allocation size"); /* * First, validate allocation parameters. Once these were regular runtime * test and elog's, but in practice Asserts seem sufficient because nobody * varies their parameters at runtime. We somewhat arbitrarily enforce a - * minimum 1K block size. + * minimum 1K block size. We restrict the maximum block size to + * MEMORYCHUNK_MAX_BLOCKOFFSET as MemoryChunks are limited to this in + * regards to addressing the offset between the chunk and the block that + * the chunk is stored on. We would be unable to store the offset between + * the chunk and block for any chunks that were beyond + * MEMORYCHUNK_MAX_BLOCKOFFSET bytes into the block if the block was to be + * larger than this. */ Assert(initBlockSize == MAXALIGN(initBlockSize) && initBlockSize >= 1024); @@ -409,6 +375,7 @@ AllocSetContextCreateInternal(MemoryContext parent, (minContextSize == MAXALIGN(minContextSize) && minContextSize >= 1024 && minContextSize <= maxBlockSize)); + Assert(maxBlockSize <= MEMORYCHUNK_MAX_BLOCKOFFSET); /* * Check whether the parameters match either available freelist. We do @@ -443,7 +410,7 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Reinitialize its header, installing correct name and parent */ MemoryContextCreate((MemoryContext) set, T_AllocSetContext, - &AllocSetMethods, + MCTX_ASET_ID, parent, name); @@ -519,7 +486,8 @@ AllocSetContextCreateInternal(MemoryContext parent, * * We have to have allocChunkLimit a power of two, because the requested * and actually-allocated sizes of any chunk must be on the same side of - * the limit, else we get confused about whether the chunk is "big". + * the limit, else we get confused about whether the chunk is on a + * dedicated block. * * Also, allocChunkLimit must not exceed ALLOCSET_SEPARATE_THRESHOLD. */ @@ -534,7 +502,7 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) set, T_AllocSetContext, - &AllocSetMethods, + MCTX_ASET_ID, parent, name); @@ -555,7 +523,7 @@ AllocSetContextCreateInternal(MemoryContext parent, * thrash malloc() when a context is repeatedly reset after small allocations, * which is typical behavior for per-tuple contexts. */ -static void +void AllocSetReset(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -623,7 +591,7 @@ AllocSetReset(MemoryContext context) * * Unlike AllocSetReset, this *must* free all resources of the set. */ -static void +void AllocSetDelete(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -717,12 +685,12 @@ AllocSetDelete(MemoryContext context) * is marked, as mcxt.c will set it to UNDEFINED. In some paths we will * return space that is marked NOACCESS - AllocSetRealloc has to beware! */ -static void * +void * AllocSetAlloc(MemoryContext context, Size size) { AllocSet set = (AllocSet) context; AllocBlock block; - AllocChunk chunk; + MemoryChunk *chunk; int fidx; Size chunk_size; Size blksize; @@ -746,18 +714,20 @@ AllocSetAlloc(MemoryContext context, Size size) block->aset = set; block->freeptr = block->endptr = ((char *) block) + blksize; - chunk = (AllocChunk) (((char *) block) + ALLOC_BLOCKHDRSZ); - chunk->aset = set; - chunk->size = chunk_size; + chunk = (MemoryChunk *) (((char *) block) + ALLOC_BLOCKHDRSZ); + + /* mark the MemoryChunk as externally managed */ + MemoryChunkSetHdrMaskExternal(chunk, MCTX_ASET_ID); + #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk_size) - set_sentinel(AllocChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* @@ -780,13 +750,13 @@ AllocSetAlloc(MemoryContext context, Size size) } /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -799,37 +769,43 @@ AllocSetAlloc(MemoryContext context, Size size) chunk = set->freelist[fidx]; if (chunk != NULL) { - Assert(chunk->size >= size); + AllocFreelistLink *link; - set->freelist[fidx] = (AllocChunk) chunk->aset; + Assert(fidx == MemoryChunkGetValue(chunk)); - chunk->aset = (void *) set; + chunk_size = GetChunkSizeFromFreelistIdx(fidx); + link = GetFreeListLink(chunk, chunk_size); + + /* pop this chunk off the freelist */ + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + set->freelist[fidx] = link->next; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(AllocChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, - chunk->size - size); + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, + chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * Choose the actual chunk size to allocate. */ - chunk_size = (1 << ALLOC_MINBITS) << fidx; + chunk_size = GetChunkSizeFromFreelistIdx(fidx); Assert(chunk_size >= size); /* @@ -856,6 +832,7 @@ AllocSetAlloc(MemoryContext context, Size size) */ while (availspace >= ((1 << ALLOC_MINBITS) + ALLOC_CHUNKHDRSZ)) { + AllocFreelistLink *link; Size availchunk = availspace - ALLOC_CHUNKHDRSZ; int a_fidx = AllocSetFreeIndex(availchunk); @@ -864,29 +841,34 @@ AllocSetAlloc(MemoryContext context, Size size) * freelist than the one we need to put this chunk on. The * exception is when availchunk is exactly a power of 2. */ - if (availchunk != ((Size) 1 << (a_fidx + ALLOC_MINBITS))) + if (availchunk != GetChunkSizeFromFreelistIdx(a_fidx)) { a_fidx--; Assert(a_fidx >= 0); - availchunk = ((Size) 1 << (a_fidx + ALLOC_MINBITS)); + availchunk = GetChunkSizeFromFreelistIdx(a_fidx); } - chunk = (AllocChunk) (block->freeptr); + chunk = (MemoryChunk *) (block->freeptr); /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, ALLOC_CHUNKHDRSZ); - block->freeptr += (availchunk + ALLOC_CHUNKHDRSZ); availspace -= (availchunk + ALLOC_CHUNKHDRSZ); - chunk->size = availchunk; + /* store the freelist index in the value field */ + MemoryChunkSetHdrMask(chunk, block, a_fidx, MCTX_ASET_ID); #ifdef MEMORY_CONTEXT_CHECKING - chunk->requested_size = 0; /* mark it free */ + chunk->requested_size = InvalidAllocSize; /* mark it free */ #endif - chunk->aset = (void *) set->freelist[a_fidx]; + /* push this chunk onto the freelist */ + link = GetFreeListLink(chunk, availchunk); + + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + link->next = set->freelist[a_fidx]; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); + set->freelist[a_fidx] = chunk; } - /* Mark that we need to create a new block */ block = NULL; } @@ -954,7 +936,7 @@ AllocSetAlloc(MemoryContext context, Size size) /* * OK, do the allocation */ - chunk = (AllocChunk) (block->freeptr); + chunk = (MemoryChunk *) (block->freeptr); /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, ALLOC_CHUNKHDRSZ); @@ -962,67 +944,68 @@ AllocSetAlloc(MemoryContext context, Size size) block->freeptr += (chunk_size + ALLOC_CHUNKHDRSZ); Assert(block->freeptr <= block->endptr); - chunk->aset = (void *) set; - chunk->size = chunk_size; + /* store the freelist index in the value field */ + MemoryChunkSetHdrMask(chunk, block, fidx, MCTX_ASET_ID); + #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(AllocChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * AllocSetFree * Frees allocated memory; memory is removed from the set. */ -static void -AllocSetFree(MemoryContext context, void *pointer) +void +AllocSetFree(void *pointer) { - AllocSet set = (AllocSet) context; - AllocChunk chunk = AllocPointerGetChunk(pointer); + AllocSet set; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); + if (MemoryChunkIsExternal(chunk)) + { + + AllocBlock block = ExternalChunkGetBlock(chunk); + + set = block->aset; + #ifdef MEMORY_CONTEXT_CHECKING - /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunk->size) - if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", - set->header.name, chunk); + { + Size chunk_size = block->endptr - (char *) pointer; + + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < chunk_size) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); + } #endif - if (chunk->size > set->allocChunkLimit) - { - /* - * Big chunks are certain to have been allocated as single-chunk - * blocks. Just unlink that block and return it to malloc(). - */ - AllocBlock block = (AllocBlock) (((char *) chunk) - ALLOC_BLOCKHDRSZ); /* - * Try to verify that we have a sane block pointer: it should - * reference the correct aset, and freeptr and endptr should point - * just past the chunk. + * Try to verify that we have a sane block pointer, the freeptr should + * match the endptr. */ - if (block->aset != set || - block->freeptr != block->endptr || - block->freeptr != ((char *) block) + - (chunk->size + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) + if (block->freeptr != block->endptr) elog(ERROR, "could not find block containing chunk %p", chunk); /* OK, remove block from aset's list and free it */ @@ -1033,7 +1016,7 @@ AllocSetFree(MemoryContext context, void *pointer) if (block->next) block->next->prev = block->prev; - context->mem_allocated -= block->endptr - ((char *) block); + set->header.mem_allocated -= block->endptr - ((char *) block); #ifdef CLOBBER_FREED_MEMORY wipe_mem(block, block->freeptr - ((char *) block)); @@ -1042,20 +1025,38 @@ AllocSetFree(MemoryContext context, void *pointer) } else { - /* Normal case, put the chunk into appropriate freelist */ - int fidx = AllocSetFreeIndex(chunk->size); + int fidx = MemoryChunkGetValue(chunk); + AllocBlock block = MemoryChunkGetBlock(chunk); + Size chunk_size = GetChunkSizeFromFreelistIdx(fidx); + AllocFreelistLink *link = GetFreeListLink(chunk, chunk_size); - chunk->aset = (void *) set->freelist[fidx]; + set = block->aset; + +#ifdef MEMORY_CONTEXT_CHECKING + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < chunk_size) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); +#endif #ifdef CLOBBER_FREED_MEMORY - wipe_mem(pointer, chunk->size); + wipe_mem(pointer, chunk_size); #endif + /* Normal case, put the chunk into appropriate freelist */ + /* push this chunk onto the top of the freelist for this chunk size */ + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + link->next = set->freelist[fidx]; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); + set->freelist[fidx] = chunk; #ifdef MEMORY_CONTEXT_CHECKING - /* Reset requested_size to 0 in chunks that are on freelist */ - chunk->requested_size = 0; + /* + * Reset requested_size to InvalidAllocSize in chunks that are on + * freelist. + */ + chunk->requested_size = InvalidAllocSize; #endif - set->freelist[fidx] = chunk; } } @@ -1071,57 +1072,48 @@ AllocSetFree(MemoryContext context, void *pointer) * (In principle, we could use VALGRIND_GET_VBITS() to rediscover the old * request size.) */ -static void * -AllocSetRealloc(MemoryContext context, void *pointer, Size size) +void * +AllocSetRealloc(void *pointer, Size size) { - AllocSet set = (AllocSet) context; - AllocChunk chunk = AllocPointerGetChunk(pointer); + AllocBlock block; + AllocSet set; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); Size oldsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - oldsize = chunk->size; - -#ifdef MEMORY_CONTEXT_CHECKING - /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < oldsize) - if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", - set->header.name, chunk); -#endif - - if (oldsize > set->allocChunkLimit) + if (MemoryChunkIsExternal(chunk)) { /* * The chunk must have been allocated as a single-chunk block. Use * realloc() to make the containing block bigger, or smaller, with * minimum space wastage. */ - AllocBlock block = (AllocBlock) (((char *) chunk) - ALLOC_BLOCKHDRSZ); Size chksize; Size blksize; Size oldblksize; + block = ExternalChunkGetBlock(chunk); + oldsize = block->endptr - (char *) pointer; + set = block->aset; + +#ifdef MEMORY_CONTEXT_CHECKING + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < oldsize) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); +#endif + /* - * Try to verify that we have a sane block pointer: it should - * reference the correct aset, and freeptr and endptr should point - * just past the chunk. + * Try to verify that we have a sane block pointer, the freeptr should + * match the endptr. */ - if (block->aset != set || - block->freeptr != block->endptr || - block->freeptr != ((char *) block) + - (oldsize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) + if (block->freeptr != block->endptr) elog(ERROR, "could not find block containing chunk %p", chunk); - /* - * Even if the new request is less than set->allocChunkLimit, we stick - * with the single-chunk block approach. Therefore we need - * chunk->size to be bigger than set->allocChunkLimit, so we don't get - * confused about the chunk's status in future calls. - */ - chksize = Max(size, set->allocChunkLimit + 1); - chksize = MAXALIGN(chksize); + chksize = MAXALIGN(size); /* Do the realloc */ blksize = chksize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ; @@ -1136,21 +1128,20 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) } /* updated separately, not to underflow when (oldblksize > blksize) */ - context->mem_allocated -= oldblksize; - context->mem_allocated += blksize; + set->header.mem_allocated -= oldblksize; + set->header.mem_allocated += blksize; block->freeptr = block->endptr = ((char *) block) + blksize; /* Update pointers since block has likely been moved */ - chunk = (AllocChunk) (((char *) block) + ALLOC_BLOCKHDRSZ); - pointer = AllocChunkGetPointer(chunk); + chunk = (MemoryChunk *) (((char *) block) + ALLOC_BLOCKHDRSZ); + pointer = MemoryChunkGetPointer(chunk); if (block->prev) block->prev->next = block; else set->blocks = block; if (block->next) block->next->prev = block; - chunk->size = chksize; #ifdef MEMORY_CONTEXT_CHECKING #ifdef RANDOMIZE_ALLOCATED_MEMORY @@ -1172,9 +1163,8 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) #endif chunk->requested_size = size; - /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) + if (size < chksize) set_sentinel(pointer, size); #else /* !MEMORY_CONTEXT_CHECKING */ @@ -1195,12 +1185,24 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) return pointer; } + block = MemoryChunkGetBlock(chunk); + oldsize = GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)); + set = block->aset; + +#ifdef MEMORY_CONTEXT_CHECKING + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < oldsize) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); +#endif + /* * Chunk sizes are aligned to power of 2 in AllocSetAlloc(). Maybe the * allocated area already is >= the new size. (In particular, we will * fall out here if the requested size is a decrease.) */ - else if (oldsize >= size) + if (oldsize >= size) { #ifdef MEMORY_CONTEXT_CHECKING Size oldrequest = chunk->requested_size; @@ -1289,34 +1291,59 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) memcpy(newPointer, pointer, oldsize); /* free old chunk */ - AllocSetFree((MemoryContext) set, pointer); + AllocSetFree(pointer); return newPointer; } } +/* + * AllocSetGetChunkContext + * Return the MemoryContext that 'pointer' belongs to. + */ +MemoryContext +AllocSetGetChunkContext(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + AllocBlock block; + AllocSet set; + + if (MemoryChunkIsExternal(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (AllocBlock) MemoryChunkGetBlock(chunk); + + set = block->aset; + + return &set->header; +} + /* * AllocSetGetChunkSpace * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -AllocSetGetChunkSpace(MemoryContext context, void *pointer) +Size +AllocSetGetChunkSpace(void *pointer) { - AllocChunk chunk = AllocPointerGetChunk(pointer); - Size result; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); - VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - result = chunk->size + ALLOC_CHUNKHDRSZ; - VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return result; + if (MemoryChunkIsExternal(chunk)) + { + AllocBlock block = ExternalChunkGetBlock(chunk); + + return block->endptr - (char *) chunk; + } + + return GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)) + + ALLOC_CHUNKHDRSZ; } /* * AllocSetIsEmpty * Is an allocset empty of any allocated space? */ -static bool +bool AllocSetIsEmpty(MemoryContext context) { /* @@ -1339,7 +1366,7 @@ AllocSetIsEmpty(MemoryContext context) * totals: if not NULL, add stats about this context into *totals. * print_to_stderr: print stats to stderr if true, elog otherwise. */ -static void +void AllocSetStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr) @@ -1363,13 +1390,21 @@ AllocSetStats(MemoryContext context, } for (fidx = 0; fidx < ALLOCSET_NUM_FREELISTS; fidx++) { - AllocChunk chunk; + MemoryChunk *chunk = set->freelist[fidx]; - for (chunk = set->freelist[fidx]; chunk != NULL; - chunk = (AllocChunk) chunk->aset) + while (chunk != NULL) { + Size chksz = GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)); + AllocFreelistLink *link = GetFreeListLink(chunk, chksz); + + Assert(GetChunkSizeFromFreelistIdx(fidx) == chksz); + freechunks++; - freespace += chunk->size + ALLOC_CHUNKHDRSZ; + freespace += chksz + ALLOC_CHUNKHDRSZ; + + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + chunk = link->next; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); } } @@ -1404,7 +1439,7 @@ AllocSetStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void AllocSetCheck(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -1421,6 +1456,7 @@ AllocSetCheck(MemoryContext context) long blk_used = block->freeptr - bpoz; long blk_data = 0; long nchunks = 0; + bool has_external_chunk = false; if (set->keeper == block) total_allocated += block->endptr - ((char *) set); @@ -1452,20 +1488,31 @@ AllocSetCheck(MemoryContext context) */ while (bpoz < block->freeptr) { - AllocChunk chunk = (AllocChunk) bpoz; + MemoryChunk *chunk = (MemoryChunk *) bpoz; + AllocBlock chunkblock; Size chsize, dsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - chsize = chunk->size; /* aligned chunk size */ + if (MemoryChunkIsExternal(chunk)) + { + chsize = block->endptr - (char *) MemoryChunkGetPointer(chunk); /* aligned chunk size */ + chunkblock = ExternalChunkGetBlock(chunk); + has_external_chunk = true; + } + else + { + chsize = GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)); /* aligned chunk size */ + chunkblock = (AllocBlock) MemoryChunkGetBlock(chunk); + } dsize = chunk->requested_size; /* real data */ /* * Check chunk size */ - if (dsize > chsize) + if (dsize != InvalidAllocSize && dsize > chsize) elog(WARNING, "problem in alloc set %s: req size > alloc size for chunk %p in block %p", name, chunk, block); if (chsize < (1 << ALLOC_MINBITS)) @@ -1478,20 +1525,15 @@ AllocSetCheck(MemoryContext context) elog(WARNING, "problem in alloc set %s: bad single-chunk %p in block %p", name, chunk, block); - /* - * If chunk is allocated, check for correct aset pointer. (If it's - * free, the aset is the freelist pointer, which we can't check as - * easily...) Note this is an incomplete test, since palloc(0) - * produces an allocated chunk with requested_size == 0. - */ - if (dsize > 0 && chunk->aset != (void *) set) - elog(WARNING, "problem in alloc set %s: bogus aset link in block %p, chunk %p", - name, block, chunk); + /* Check the block offset correctly matches this block */ + if (block != chunkblock) + elog(WARNING, "problem in alloc set %s: bad block offset for chunk %p in block %p", + name, chunk, block); /* * Check for overwrite of padding space in an allocated chunk. */ - if (chunk->aset == (void *) set && dsize < chsize && + if (dsize != InvalidAllocSize && dsize < chsize && !sentinel_ok(chunk, ALLOC_CHUNKHDRSZ + dsize)) elog(WARNING, "problem in alloc set %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); @@ -1500,7 +1542,7 @@ AllocSetCheck(MemoryContext context) * If chunk is allocated, disallow external access to private part * of chunk header. */ - if (chunk->aset == (void *) set) + if (dsize != InvalidAllocSize) VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); blk_data += chsize; @@ -1512,6 +1554,10 @@ AllocSetCheck(MemoryContext context) if ((blk_data + (nchunks * ALLOC_CHUNKHDRSZ)) != blk_used) elog(WARNING, "problem in alloc set %s: found inconsistent memory block %p", name, block); + + if (has_external_chunk && nchunks > 1) + elog(WARNING, "problem in alloc set %s: external chunk on non-dedicated block %p", + name, block); } Assert(total_allocated == context->mem_allocated); diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index e530e272e0..9ad4b9fcfb 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -39,15 +39,16 @@ #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" #define Generation_BLOCKHDRSZ MAXALIGN(sizeof(GenerationBlock)) -#define Generation_CHUNKHDRSZ sizeof(GenerationChunk) +#define Generation_CHUNKHDRSZ sizeof(MemoryChunk) #define Generation_CHUNK_FRACTION 8 typedef struct GenerationBlock GenerationBlock; /* forward reference */ -typedef struct GenerationChunk GenerationChunk; typedef void *GenerationPointer; @@ -89,6 +90,7 @@ typedef struct GenerationContext struct GenerationBlock { dlist_node node; /* doubly-linked list of blocks */ + GenerationContext *context; /* pointer back to the owning context */ Size blksize; /* allocated size of this block */ int nchunks; /* number of chunks in the block */ int nfree; /* number of free chunks */ @@ -97,104 +99,36 @@ struct GenerationBlock }; /* - * GenerationChunk - * The prefix of each piece of memory in a GenerationBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "context" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). We simplify matters for this - * module by requiring sizeof(GenerationChunk) to be maxaligned, and then - * we can ensure things work by adding any required alignment padding before - * the pointer fields. There is a static assertion below that the alignment - * is done correctly. - */ -struct GenerationChunk -{ - /* size is always the size of the usable space in the chunk */ - Size size; -#ifdef MEMORY_CONTEXT_CHECKING - /* when debugging memory usage, also store actual requested size */ - /* this is zero in a free chunk */ - Size requested_size; - -#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T * 2 + SIZEOF_VOID_P * 2) -#else -#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P * 2) -#endif /* MEMORY_CONTEXT_CHECKING */ - - /* ensure proper alignment by adding padding if needed */ -#if (GENERATIONCHUNK_RAWSIZE % MAXIMUM_ALIGNOF) != 0 - char padding[MAXIMUM_ALIGNOF - GENERATIONCHUNK_RAWSIZE % MAXIMUM_ALIGNOF]; -#endif - - GenerationBlock *block; /* block owning this chunk */ - GenerationContext *context; /* owning context, or NULL if freed chunk */ - /* there must not be any padding to reach a MAXALIGN boundary here! */ -}; - -/* - * Only the "context" field should be accessed outside this module. + * Only the "hdrmask" field should be accessed outside this module. * We keep the rest of an allocated chunk's header marked NOACCESS when using * valgrind. But note that freed chunk headers are kept accessible, for * simplicity. */ -#define GENERATIONCHUNK_PRIVATE_LEN offsetof(GenerationChunk, context) - +#define GENERATIONCHUNK_PRIVATE_LEN offsetof(MemoryChunk, hdrmask) /* * GenerationIsValid * True iff set is valid allocation set. */ #define GenerationIsValid(set) PointerIsValid(set) -#define GenerationPointerGetChunk(ptr) \ - ((GenerationChunk *)(((char *)(ptr)) - Generation_CHUNKHDRSZ)) -#define GenerationChunkGetPointer(chk) \ - ((GenerationPointer *)(((char *)(chk)) + Generation_CHUNKHDRSZ)) +/* + * We always store external chunks on a dedicated block. This makes fetching + * the block from an external chunk easy since it's always the first and only + * chunk on the block. + */ +#define ExternalChunkGetBlock(chunk) \ + (GenerationBlock *) ((char *) chunk - Generation_BLOCKHDRSZ) /* Inlined helper functions */ -static inline void GenerationBlockInit(GenerationBlock *block, Size blksize); +static inline void GenerationBlockInit(GenerationContext *context, + GenerationBlock *block, + Size blksize); static inline bool GenerationBlockIsEmpty(GenerationBlock *block); static inline void GenerationBlockMarkEmpty(GenerationBlock *block); static inline Size GenerationBlockFreeBytes(GenerationBlock *block); static inline void GenerationBlockFree(GenerationContext *set, GenerationBlock *block); -/* - * These functions implement the MemoryContext API for Generation contexts. - */ -static void *GenerationAlloc(MemoryContext context, Size size); -static void GenerationFree(MemoryContext context, void *pointer); -static void *GenerationRealloc(MemoryContext context, void *pointer, Size size); -static void GenerationReset(MemoryContext context); -static void GenerationDelete(MemoryContext context); -static Size GenerationGetChunkSpace(MemoryContext context, void *pointer); -static bool GenerationIsEmpty(MemoryContext context); -static void GenerationStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); - -#ifdef MEMORY_CONTEXT_CHECKING -static void GenerationCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for Generation contexts. - */ -static const MemoryContextMethods GenerationMethods = { - GenerationAlloc, - GenerationFree, - GenerationRealloc, - GenerationReset, - GenerationDelete, - GenerationGetChunkSpace, - GenerationIsEmpty, - GenerationStats -#ifdef MEMORY_CONTEXT_CHECKING - ,GenerationCheck -#endif -}; - /* * Public routines @@ -223,17 +157,20 @@ GenerationContextCreate(MemoryContext parent, GenerationContext *set; GenerationBlock *block; - /* Assert we padded GenerationChunk properly */ + /* ensure MemoryChunk's size is properly maxaligned */ StaticAssertStmt(Generation_CHUNKHDRSZ == MAXALIGN(Generation_CHUNKHDRSZ), - "sizeof(GenerationChunk) is not maxaligned"); - StaticAssertStmt(offsetof(GenerationChunk, context) + sizeof(MemoryContext) == - Generation_CHUNKHDRSZ, - "padding calculation in GenerationChunk is wrong"); + "sizeof(MemoryChunk) is not maxaligned"); /* * First, validate allocation parameters. Asserts seem sufficient because * nobody varies their parameters at runtime. We somewhat arbitrarily - * enforce a minimum 1K block size. + * enforce a minimum 1K block size. We restrict the maximum block size to + * MEMORYCHUNK_MAX_BLOCKOFFSET as MemoryChunks are limited to this in + * regards to addressing the offset between the chunk and the block that + * the chunk is stored on. We would be unable to store the offset between + * the chunk and block for any chunks that were beyond + * MEMORYCHUNK_MAX_BLOCKOFFSET bytes into the block if the block was to be + * larger than this. */ Assert(initBlockSize == MAXALIGN(initBlockSize) && initBlockSize >= 1024); @@ -244,6 +181,7 @@ GenerationContextCreate(MemoryContext parent, (minContextSize == MAXALIGN(minContextSize) && minContextSize >= 1024 && minContextSize <= maxBlockSize)); + Assert(maxBlockSize <= MEMORYCHUNK_MAX_BLOCKOFFSET); /* Determine size of initial block */ allocSize = MAXALIGN(sizeof(GenerationContext)) + @@ -278,7 +216,7 @@ GenerationContextCreate(MemoryContext parent, block = (GenerationBlock *) (((char *) set) + MAXALIGN(sizeof(GenerationContext))); /* determine the block size and initialize it */ firstBlockSize = allocSize - MAXALIGN(sizeof(GenerationContext)); - GenerationBlockInit(block, firstBlockSize); + GenerationBlockInit(set, block, firstBlockSize); /* add it to the doubly-linked list of blocks */ dlist_push_head(&set->blocks, &block->node); @@ -300,9 +238,14 @@ GenerationContextCreate(MemoryContext parent, /* * Compute the allocation chunk size limit for this context. * - * Follows similar ideas as AllocSet, see aset.c for details ... + * Limit the maximum size a non-dedicated chunk can be so that we can fit + * at least Generation_CHUNK_FRACTION of chunks this big onto the maximum + * sized block. We must further limit this value so that it's no more + * than MEMORYCHUNK_MAX_VALUE. We're unable to have non-dedicated chunks + * larger than that value as we store the chunk size in the MemoryChunk + * 'value' field in the call to MemoryChunkSetHdrMask(). */ - set->allocChunkLimit = maxBlockSize; + set->allocChunkLimit = Min(maxBlockSize, MEMORYCHUNK_MAX_VALUE); while ((Size) (set->allocChunkLimit + Generation_CHUNKHDRSZ) > (Size) ((Size) (maxBlockSize - Generation_BLOCKHDRSZ) / Generation_CHUNK_FRACTION)) set->allocChunkLimit >>= 1; @@ -310,7 +253,7 @@ GenerationContextCreate(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) set, T_GenerationContext, - &GenerationMethods, + MCTX_GENERATION_ID, parent, name); @@ -326,7 +269,7 @@ GenerationContextCreate(MemoryContext parent, * The code simply frees all the blocks in the context - we don't keep any * keeper blocks or anything like that. */ -static void +void GenerationReset(MemoryContext context) { GenerationContext *set = (GenerationContext *) context; @@ -371,7 +314,7 @@ GenerationReset(MemoryContext context) * GenerationDelete * Free all memory which is allocated in the given context. */ -static void +void GenerationDelete(MemoryContext context) { /* Reset to release all releasable GenerationBlocks */ @@ -393,12 +336,12 @@ GenerationDelete(MemoryContext context) * is marked, as mcxt.c will set it to UNDEFINED. In some paths we will * return space that is marked NOACCESS - GenerationRealloc has to beware! */ -static void * +void * GenerationAlloc(MemoryContext context, Size size) { GenerationContext *set = (GenerationContext *) context; GenerationBlock *block; - GenerationChunk *chunk; + MemoryChunk *chunk; Size chunk_size = MAXALIGN(size); Size required_size = chunk_size + Generation_CHUNKHDRSZ; @@ -414,6 +357,7 @@ GenerationAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; /* block with a single (used) chunk */ + block->context = set; block->blksize = blksize; block->nchunks = 1; block->nfree = 0; @@ -421,33 +365,33 @@ GenerationAlloc(MemoryContext context, Size size) /* the block is completely full */ block->freeptr = block->endptr = ((char *) block) + blksize; - chunk = (GenerationChunk *) (((char *) block) + Generation_BLOCKHDRSZ); - chunk->block = block; - chunk->context = set; - chunk->size = chunk_size; + chunk = (MemoryChunk *) (((char *) block) + Generation_BLOCKHDRSZ); + + /* mark the MemoryChunk as externally managed */ + MemoryChunkSetHdrMaskExternal(chunk, MCTX_GENERATION_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk_size) - set_sentinel(GenerationChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) GenerationChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* add the block to the list of allocated blocks */ dlist_push_head(&set->blocks, &block->node); /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) GenerationChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return GenerationChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -516,7 +460,7 @@ GenerationAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; /* initialize the new block */ - GenerationBlockInit(block, blksize); + GenerationBlockInit(set, block, blksize); /* add it to the doubly-linked list of blocks */ dlist_push_head(&set->blocks, &block->node); @@ -533,7 +477,7 @@ GenerationAlloc(MemoryContext context, Size size) Assert(block != NULL); Assert((block->endptr - block->freeptr) >= Generation_CHUNKHDRSZ + chunk_size); - chunk = (GenerationChunk *) block->freeptr; + chunk = (MemoryChunk *) block->freeptr; /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, Generation_CHUNKHDRSZ); @@ -543,29 +487,26 @@ GenerationAlloc(MemoryContext context, Size size) Assert(block->freeptr <= block->endptr); - chunk->block = block; - chunk->context = set; - chunk->size = chunk_size; - + MemoryChunkSetHdrMask(chunk, block, chunk_size, MCTX_GENERATION_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(GenerationChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) GenerationChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) GenerationChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return GenerationChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -574,8 +515,10 @@ GenerationAlloc(MemoryContext context, Size size) * mem_allocated field. */ static inline void -GenerationBlockInit(GenerationBlock *block, Size blksize) +GenerationBlockInit(GenerationContext *context, GenerationBlock *block, + Size blksize) { + block->context = context; block->blksize = blksize; block->nchunks = 0; block->nfree = 0; @@ -661,36 +604,49 @@ GenerationBlockFree(GenerationContext *set, GenerationBlock *block) * Update number of chunks in the block, and if all chunks in the block * are now free then discard the block. */ -static void -GenerationFree(MemoryContext context, void *pointer) +void +GenerationFree(void *pointer) { - GenerationContext *set = (GenerationContext *) context; - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); GenerationBlock *block; + GenerationContext *set; +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + Size chunksize; +#endif + + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + chunksize = block->endptr - (char *) pointer; +#endif + } + else + { + block = MemoryChunkGetBlock(chunk); +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + chunksize = MemoryChunkGetValue(chunk); +#endif + } /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - block = chunk->block; - #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunk->size) + if (chunk->requested_size < chunksize) if (!sentinel_ok(pointer, chunk->requested_size)) elog(WARNING, "detected write past chunk end in %s %p", - ((MemoryContext) set)->name, chunk); + ((MemoryContext) block->context)->name, chunk); #endif #ifdef CLOBBER_FREED_MEMORY - wipe_mem(pointer, chunk->size); + wipe_mem(pointer, chunksize); #endif - /* Reset context to NULL in freed chunks */ - chunk->context = NULL; - #ifdef MEMORY_CONTEXT_CHECKING - /* Reset requested_size to 0 in freed chunks */ - chunk->requested_size = 0; + /* Reset requested_size to InvalidAllocSize in freed chunks */ + chunk->requested_size = InvalidAllocSize; #endif block->nfree += 1; @@ -702,6 +658,8 @@ GenerationFree(MemoryContext context, void *pointer) if (block->nfree < block->nchunks) return; + set = block->context; + /* Don't try to free the keeper block, just mark it empty */ if (block == set->keeper) { @@ -732,7 +690,7 @@ GenerationFree(MemoryContext context, void *pointer) */ dlist_delete(&block->node); - context->mem_allocated -= block->blksize; + set->header.mem_allocated -= block->blksize; free(block); } @@ -742,18 +700,30 @@ GenerationFree(MemoryContext context, void *pointer) * and discard the old one. The only exception is when the new size fits * into the old chunk - in that case we just update chunk header. */ -static void * -GenerationRealloc(MemoryContext context, void *pointer, Size size) +void * +GenerationRealloc(void *pointer, Size size) { - GenerationContext *set = (GenerationContext *) context; - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationContext *set; + GenerationBlock *block; GenerationPointer newPointer; Size oldsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - oldsize = chunk->size; + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); + oldsize = block->endptr - (char *) pointer; + } + else + { + block = MemoryChunkGetBlock(chunk); + oldsize = MemoryChunkGetValue(chunk); + } + + set = block->context; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ @@ -848,7 +818,7 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) memcpy(newPointer, pointer, oldsize); /* free old chunk */ - GenerationFree((MemoryContext) set, pointer); + GenerationFree(pointer); return newPointer; } @@ -858,23 +828,47 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -GenerationGetChunkSpace(MemoryContext context, void *pointer) +MemoryContext +GenerationGetChunkContext(void *pointer) { - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); - Size result; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationBlock *block; - VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - result = chunk->size + Generation_CHUNKHDRSZ; - VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return result; + if (MemoryChunkIsExternal(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (GenerationBlock *) MemoryChunkGetBlock(chunk); + + return &block->context->header; +} + +/* + * GenerationGetChunkSpace + * Given a currently-allocated chunk, determine the total space + * it occupies (including all memory-allocation overhead). + */ +Size +GenerationGetChunkSpace(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + Size chunksize; + + if (MemoryChunkIsExternal(chunk)) + { + GenerationBlock *block = ExternalChunkGetBlock(chunk); + chunksize = block->endptr - (char *) pointer; + } + else + chunksize = MemoryChunkGetValue(chunk); + + return Generation_CHUNKHDRSZ + chunksize; } /* * GenerationIsEmpty * Is a GenerationContext empty of any allocated space? */ -static bool +bool GenerationIsEmpty(MemoryContext context) { GenerationContext *set = (GenerationContext *) context; @@ -903,7 +897,7 @@ GenerationIsEmpty(MemoryContext context) * XXX freespace only accounts for empty space at the end of the block, not * space of freed chunks (which is unknown). */ -static void +void GenerationStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr) @@ -961,7 +955,7 @@ GenerationStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void GenerationCheck(MemoryContext context) { GenerationContext *gen = (GenerationContext *) context; @@ -976,6 +970,7 @@ GenerationCheck(MemoryContext context) int nfree, nchunks; char *ptr; + bool has_external_chunk = false; total_allocated += block->blksize; @@ -987,6 +982,11 @@ GenerationCheck(MemoryContext context) elog(WARNING, "problem in Generation %s: number of free chunks %d in block %p exceeds %d allocated", name, block->nfree, block, block->nchunks); + /* check block belongs to the correct context */ + if (block->context != gen) + elog(WARNING, "problem in Generation %s: bogus context link in block %p", + name, block); + /* Now walk through the chunks and count them. */ nfree = 0; nchunks = 0; @@ -994,42 +994,47 @@ GenerationCheck(MemoryContext context) while (ptr < block->freeptr) { - GenerationChunk *chunk = (GenerationChunk *) ptr; + MemoryChunk *chunk = (MemoryChunk *) ptr; + GenerationBlock *chunkblock; + Size chunksize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); + if (MemoryChunkIsExternal(chunk)) + { + chunkblock = ExternalChunkGetBlock(chunk); + chunksize = block->endptr - (char *) MemoryChunkGetPointer(chunk); + has_external_chunk = true; + } + else + { + chunkblock = MemoryChunkGetBlock(chunk); + chunksize = MemoryChunkGetValue(chunk); + } + /* move to the next chunk */ - ptr += (chunk->size + Generation_CHUNKHDRSZ); + ptr += (chunksize + Generation_CHUNKHDRSZ); nchunks += 1; /* chunks have both block and context pointers, so check both */ - if (chunk->block != block) + if (chunkblock != block) elog(WARNING, "problem in Generation %s: bogus block link in block %p, chunk %p", name, block, chunk); - /* - * Check for valid context pointer. Note this is an incomplete - * test, since palloc(0) produces an allocated chunk with - * requested_size == 0. - */ - if ((chunk->requested_size > 0 && chunk->context != gen) || - (chunk->context != gen && chunk->context != NULL)) - elog(WARNING, "problem in Generation %s: bogus context link in block %p, chunk %p", - name, block, chunk); - - /* now make sure the chunk size is correct */ - if (chunk->size < chunk->requested_size || - chunk->size != MAXALIGN(chunk->size)) - elog(WARNING, "problem in Generation %s: bogus chunk size in block %p, chunk %p", - name, block, chunk); /* is chunk allocated? */ - if (chunk->context != NULL) + if (chunk->requested_size != InvalidAllocSize) { - /* check sentinel, but only in allocated blocks */ - if (chunk->requested_size < chunk->size && + /* now make sure the chunk size is correct */ + if (chunksize < chunk->requested_size || + chunksize != MAXALIGN(chunksize)) + elog(WARNING, "problem in Generation %s: bogus chunk size in block %p, chunk %p", + name, block, chunk); + + /* check sentinel */ + if (chunk->requested_size < chunksize && !sentinel_ok(chunk, Generation_CHUNKHDRSZ + chunk->requested_size)) elog(WARNING, "problem in Generation %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); @@ -1041,7 +1046,7 @@ GenerationCheck(MemoryContext context) * If chunk is allocated, disallow external access to private part * of chunk header. */ - if (chunk->context != NULL) + if (chunk->requested_size != InvalidAllocSize) VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); } @@ -1056,6 +1061,11 @@ GenerationCheck(MemoryContext context) if (nfree != block->nfree) elog(WARNING, "problem in Generation %s: number of free chunks %d in block %p does not match header %d", name, nfree, block, block->nfree); + + if (has_external_chunk && nchunks > 1) + elog(WARNING, "problem in Generation %s: external chunk on non-dedicated block %p", + name, block); + } Assert(total_allocated == context->mem_allocated); diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index e12be1b9bd..7c53222b9d 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -29,12 +29,57 @@ #include "utils/fmgrprotos.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_internal.h" /***************************************************************************** * GLOBAL MEMORY * *****************************************************************************/ +static const MemoryContextMethods mcxt_methods[] = { + /* aset.c */ + [MCTX_ASET_ID].alloc = AllocSetAlloc, + [MCTX_ASET_ID].free_p = AllocSetFree, + [MCTX_ASET_ID].realloc = AllocSetRealloc, + [MCTX_ASET_ID].reset = AllocSetReset, + [MCTX_ASET_ID].delete_context = AllocSetDelete, + [MCTX_ASET_ID].get_chunk_context = AllocSetGetChunkContext, + [MCTX_ASET_ID].get_chunk_space = AllocSetGetChunkSpace, + [MCTX_ASET_ID].is_empty = AllocSetIsEmpty, + [MCTX_ASET_ID].stats = AllocSetStats, +#ifdef MEMORY_CONTEXT_CHECKING + [MCTX_ASET_ID].check = AllocSetCheck, +#endif + + /* generation.c */ + [MCTX_GENERATION_ID].alloc = GenerationAlloc, + [MCTX_GENERATION_ID].free_p = GenerationFree, + [MCTX_GENERATION_ID].realloc = GenerationRealloc, + [MCTX_GENERATION_ID].reset = GenerationReset, + [MCTX_GENERATION_ID].delete_context = GenerationDelete, + [MCTX_GENERATION_ID].get_chunk_context = GenerationGetChunkContext, + [MCTX_GENERATION_ID].get_chunk_space = GenerationGetChunkSpace, + [MCTX_GENERATION_ID].is_empty = GenerationIsEmpty, + [MCTX_GENERATION_ID].stats = GenerationStats, +#ifdef MEMORY_CONTEXT_CHECKING + [MCTX_GENERATION_ID].check = GenerationCheck, +#endif + + /* slab.c */ + [MCTX_SLAB_ID].alloc = SlabAlloc, + [MCTX_SLAB_ID].free_p = SlabFree, + [MCTX_SLAB_ID].realloc = SlabRealloc, + [MCTX_SLAB_ID].reset = SlabReset, + [MCTX_SLAB_ID].delete_context = SlabDelete, + [MCTX_SLAB_ID].get_chunk_context = SlabGetChunkContext, + [MCTX_SLAB_ID].get_chunk_space = SlabGetChunkSpace, + [MCTX_SLAB_ID].is_empty = SlabIsEmpty, + [MCTX_SLAB_ID].stats = SlabStats +#ifdef MEMORY_CONTEXT_CHECKING + ,[MCTX_SLAB_ID].check = SlabCheck +#endif +}; + /* * CurrentMemoryContext * Default memory context for allocations. @@ -73,6 +118,13 @@ static void MemoryContextStatsPrint(MemoryContext context, void *passthru, #define AssertNotInCriticalSection(context) \ Assert(CritSectionCount == 0 || (context)->allowInCritSection) +/* + * Call the given function in the MemoryContextMethods for the memory context + * type that 'pointer' belongs to. + */ +#define MCXT_METHOD(pointer, method) \ + mcxt_methods[GetMemoryChunkMethodID(pointer)].method + /***************************************************************************** * EXPORTED ROUTINES * @@ -422,6 +474,17 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) context->allowInCritSection = allow; } +/* + * GetMemoryChunkContext + * Given a currently-allocated chunk, determine the MemoryContext that + * the chunk belongs to. + */ +MemoryContext +GetMemoryChunkContext(void *pointer) +{ + return MCXT_METHOD(pointer, get_chunk_context) (pointer); +} + /* * GetMemoryChunkSpace * Given a currently-allocated chunk, determine the total space @@ -433,9 +496,7 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) Size GetMemoryChunkSpace(void *pointer) { - MemoryContext context = GetMemoryChunkContext(pointer); - - return context->methods->get_chunk_space(context, pointer); + return MCXT_METHOD(pointer, get_chunk_space) (pointer); } /* @@ -814,7 +875,7 @@ MemoryContextContains(MemoryContext context, void *pointer) void MemoryContextCreate(MemoryContext node, NodeTag tag, - const MemoryContextMethods *methods, + MemoryContextMethodID method_id, MemoryContext parent, const char *name) { @@ -824,7 +885,7 @@ MemoryContextCreate(MemoryContext node, /* Initialize all standard fields of memory context header */ node->type = tag; node->isReset = true; - node->methods = methods; + node->methods = &mcxt_methods[method_id]; node->parent = parent; node->firstchild = NULL; node->mem_allocated = 0; @@ -1174,9 +1235,11 @@ palloc_extended(Size size, int flags) void pfree(void *pointer) { +#ifdef USE_VALGRIND MemoryContext context = GetMemoryChunkContext(pointer); +#endif - context->methods->free_p(context, pointer); + MCXT_METHOD(pointer, free_p) (pointer); VALGRIND_MEMPOOL_FREE(context, pointer); } @@ -1187,7 +1250,9 @@ pfree(void *pointer) void * repalloc(void *pointer, Size size) { +#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND) MemoryContext context = GetMemoryChunkContext(pointer); +#endif void *ret; if (!AllocSizeIsValid(size)) @@ -1198,15 +1263,17 @@ repalloc(void *pointer, Size size) /* isReset must be false already */ Assert(!context->isReset); - ret = context->methods->realloc(context, pointer, size); + ret = MCXT_METHOD(pointer, realloc) (pointer, size); if (unlikely(ret == NULL)) { + MemoryContext cxt = GetMemoryChunkContext(pointer); + MemoryContextStats(TopMemoryContext); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"), errdetail("Failed on request of size %zu in memory context \"%s\".", - size, context->name))); + size, cxt->name))); } VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size); @@ -1257,7 +1324,9 @@ MemoryContextAllocHuge(MemoryContext context, Size size) void * repalloc_huge(void *pointer, Size size) { +#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND) MemoryContext context = GetMemoryChunkContext(pointer); +#endif void *ret; if (!AllocHugeSizeIsValid(size)) @@ -1268,15 +1337,17 @@ repalloc_huge(void *pointer, Size size) /* isReset must be false already */ Assert(!context->isReset); - ret = context->methods->realloc(context, pointer, size); + ret = MCXT_METHOD(pointer, realloc) (pointer, size); if (unlikely(ret == NULL)) { + MemoryContext cxt = GetMemoryChunkContext(pointer); + MemoryContextStats(TopMemoryContext); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"), errdetail("Failed on request of size %zu in memory context \"%s\".", - size, context->name))); + size, cxt->name))); } VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size); diff --git a/src/backend/utils/mmgr/slab.c b/src/backend/utils/mmgr/slab.c index 67d97b22e5..e042e596f7 100644 --- a/src/backend/utils/mmgr/slab.c +++ b/src/backend/utils/mmgr/slab.c @@ -55,6 +55,8 @@ #include "lib/ilist.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" /* * SlabContext is a specialized implementation of MemoryContext. @@ -90,75 +92,23 @@ typedef struct SlabBlock dlist_node node; /* doubly-linked list */ int nfree; /* number of free chunks */ int firstFreeChunk; /* index of the first free chunk in the block */ -} SlabBlock; - -/* - * SlabChunk - * The prefix of each piece of memory in a SlabBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "slab" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). Since we support no machines on - * which MAXALIGN is more than twice sizeof(void *), this happens without any - * special hacking in this struct declaration. But there is a static - * assertion below that the alignment is done correctly. - */ -typedef struct SlabChunk -{ - SlabBlock *block; /* block owning this chunk */ SlabContext *slab; /* owning context */ - /* there must not be any padding to reach a MAXALIGN boundary here! */ -} SlabChunk; +} SlabBlock; +#define Slab_CHUNKHDRSZ sizeof(MemoryChunk) #define SlabPointerGetChunk(ptr) \ - ((SlabChunk *)(((char *)(ptr)) - sizeof(SlabChunk))) + ((MemoryChunk *)(((char *)(ptr)) - sizeof(MemoryChunk))) #define SlabChunkGetPointer(chk) \ - ((void *)(((char *)(chk)) + sizeof(SlabChunk))) + ((void *)(((char *)(chk)) + sizeof(MemoryChunk))) #define SlabBlockGetChunk(slab, block, idx) \ - ((SlabChunk *) ((char *) (block) + sizeof(SlabBlock) \ + ((MemoryChunk *) ((char *) (block) + sizeof(SlabBlock) \ + (idx * slab->fullChunkSize))) #define SlabBlockStart(block) \ ((char *) block + sizeof(SlabBlock)) #define SlabChunkIndex(slab, block, chunk) \ (((char *) chunk - SlabBlockStart(block)) / slab->fullChunkSize) -/* - * These functions implement the MemoryContext API for Slab contexts. - */ -static void *SlabAlloc(MemoryContext context, Size size); -static void SlabFree(MemoryContext context, void *pointer); -static void *SlabRealloc(MemoryContext context, void *pointer, Size size); -static void SlabReset(MemoryContext context); -static void SlabDelete(MemoryContext context); -static Size SlabGetChunkSpace(MemoryContext context, void *pointer); -static bool SlabIsEmpty(MemoryContext context); -static void SlabStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); -#ifdef MEMORY_CONTEXT_CHECKING -static void SlabCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for Slab contexts. - */ -static const MemoryContextMethods SlabMethods = { - SlabAlloc, - SlabFree, - SlabRealloc, - SlabReset, - SlabDelete, - SlabGetChunkSpace, - SlabIsEmpty, - SlabStats -#ifdef MEMORY_CONTEXT_CHECKING - ,SlabCheck -#endif -}; - - /* * SlabContextCreate * Create a new Slab context. @@ -168,8 +118,7 @@ static const MemoryContextMethods SlabMethods = { * blockSize: allocation block size * chunkSize: allocation chunk size * - * The chunkSize may not exceed: - * MAXALIGN_DOWN(SIZE_MAX) - MAXALIGN(sizeof(SlabBlock)) - sizeof(SlabChunk) + * The MAXALIGN(chunkSize) may not exceed MEMORYCHUNK_MAX_VALUE */ MemoryContext SlabContextCreate(MemoryContext parent, @@ -184,19 +133,14 @@ SlabContextCreate(MemoryContext parent, SlabContext *slab; int i; - /* Assert we padded SlabChunk properly */ - StaticAssertStmt(sizeof(SlabChunk) == MAXALIGN(sizeof(SlabChunk)), - "sizeof(SlabChunk) is not maxaligned"); - StaticAssertStmt(offsetof(SlabChunk, slab) + sizeof(MemoryContext) == - sizeof(SlabChunk), - "padding calculation in SlabChunk is wrong"); + Assert(MAXALIGN(chunkSize) <= MEMORYCHUNK_MAX_VALUE); /* Make sure the linked list node fits inside a freed chunk */ if (chunkSize < sizeof(int)) chunkSize = sizeof(int); /* chunk, including SLAB header (both addresses nicely aligned) */ - fullChunkSize = sizeof(SlabChunk) + MAXALIGN(chunkSize); + fullChunkSize = Slab_CHUNKHDRSZ + MAXALIGN(chunkSize); /* Make sure the block can store at least one chunk. */ if (blockSize < fullChunkSize + sizeof(SlabBlock)) @@ -265,7 +209,7 @@ SlabContextCreate(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) slab, T_SlabContext, - &SlabMethods, + MCTX_SLAB_ID, parent, name); @@ -279,7 +223,7 @@ SlabContextCreate(MemoryContext parent, * The code simply frees all the blocks in the context - we don't keep any * keeper blocks or anything like that. */ -static void +void SlabReset(MemoryContext context) { int i; @@ -322,7 +266,7 @@ SlabReset(MemoryContext context) * SlabDelete * Free all memory which is allocated in the given context. */ -static void +void SlabDelete(MemoryContext context) { /* Reset to release all the SlabBlocks */ @@ -336,12 +280,12 @@ SlabDelete(MemoryContext context) * Returns pointer to allocated memory of given size or NULL if * request could not be completed; memory is added to the slab. */ -static void * +void * SlabAlloc(MemoryContext context, Size size) { SlabContext *slab = castNode(SlabContext, context); SlabBlock *block; - SlabChunk *chunk; + MemoryChunk *chunk; int idx; Assert(slab); @@ -370,6 +314,7 @@ SlabAlloc(MemoryContext context, Size size) block->nfree = slab->chunksPerBlock; block->firstFreeChunk = 0; + block->slab = slab; /* * Put all the chunks on a freelist. Walk the chunks and point each @@ -378,7 +323,7 @@ SlabAlloc(MemoryContext context, Size size) for (idx = 0; idx < slab->chunksPerBlock; idx++) { chunk = SlabBlockGetChunk(slab, block, idx); - *(int32 *) SlabChunkGetPointer(chunk) = (idx + 1); + *(int32 *) MemoryChunkGetPointer(chunk) = (idx + 1); } /* @@ -426,8 +371,8 @@ SlabAlloc(MemoryContext context, Size size) * Remove the chunk from the freelist head. The index of the next free * chunk is stored in the chunk itself. */ - VALGRIND_MAKE_MEM_DEFINED(SlabChunkGetPointer(chunk), sizeof(int32)); - block->firstFreeChunk = *(int32 *) SlabChunkGetPointer(chunk); + VALGRIND_MAKE_MEM_DEFINED(MemoryChunkGetPointer(chunk), sizeof(int32)); + block->firstFreeChunk = *(int32 *) MemoryChunkGetPointer(chunk); Assert(block->firstFreeChunk >= 0); Assert(block->firstFreeChunk <= slab->chunksPerBlock); @@ -464,47 +409,47 @@ SlabAlloc(MemoryContext context, Size size) slab->minFreeChunks = 0; /* Prepare to initialize the chunk header. */ - VALGRIND_MAKE_MEM_UNDEFINED(chunk, sizeof(SlabChunk)); - - chunk->block = block; - chunk->slab = slab; + VALGRIND_MAKE_MEM_UNDEFINED(chunk, Slab_CHUNKHDRSZ); + MemoryChunkSetHdrMask(chunk, block, MAXALIGN(slab->chunkSize), + MCTX_SLAB_ID); #ifdef MEMORY_CONTEXT_CHECKING /* slab mark to catch clobber of "unused" space */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) { - set_sentinel(SlabChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); VALGRIND_MAKE_MEM_NOACCESS(((char *) chunk) + - sizeof(SlabChunk) + slab->chunkSize, + Slab_CHUNKHDRSZ + slab->chunkSize, slab->fullChunkSize - - (slab->chunkSize + sizeof(SlabChunk))); + (slab->chunkSize + Slab_CHUNKHDRSZ)); } #endif + #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) SlabChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif Assert(slab->nblocks * slab->blockSize == context->mem_allocated); - return SlabChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * SlabFree * Frees allocated memory; memory is removed from the slab. */ -static void -SlabFree(MemoryContext context, void *pointer) +void +SlabFree(void *pointer) { int idx; - SlabContext *slab = castNode(SlabContext, context); - SlabChunk *chunk = SlabPointerGetChunk(pointer); - SlabBlock *block = chunk->block; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) if (!sentinel_ok(pointer, slab->chunkSize)) elog(WARNING, "detected write past chunk end in %s %p", slab->header.name, chunk); @@ -560,13 +505,13 @@ SlabFree(MemoryContext context, void *pointer) { free(block); slab->nblocks--; - context->mem_allocated -= slab->blockSize; + slab->header.mem_allocated -= slab->blockSize; } else dlist_push_head(&slab->freelist[block->nfree], &block->node); Assert(slab->nblocks >= 0); - Assert(slab->nblocks * slab->blockSize == context->mem_allocated); + Assert(slab->nblocks * slab->blockSize == slab->header.mem_allocated); } /* @@ -582,13 +527,14 @@ SlabFree(MemoryContext context, void *pointer) * rather pointless - Slab is meant for chunks of constant size, and moreover * realloc is usually used to enlarge the chunk. */ -static void * -SlabRealloc(MemoryContext context, void *pointer, Size size) +void * +SlabRealloc(void *pointer, Size size) { - SlabContext *slab = castNode(SlabContext, context); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; Assert(slab); - /* can't do actual realloc with slab, but let's try to be gentle */ if (size == slab->chunkSize) return pointer; @@ -597,15 +543,33 @@ SlabRealloc(MemoryContext context, void *pointer, Size size) return NULL; /* keep compiler quiet */ } +/* + * SlabGetChunkContext + * Return the MemoryContext that 'pointer' belongs to. + */ +MemoryContext +SlabGetChunkContext(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; + + Assert(slab != NULL); + + return &slab->header; +} + /* * SlabGetChunkSpace * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -SlabGetChunkSpace(MemoryContext context, void *pointer) +Size +SlabGetChunkSpace(void *pointer) { - SlabContext *slab = castNode(SlabContext, context); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; Assert(slab); @@ -616,7 +580,7 @@ SlabGetChunkSpace(MemoryContext context, void *pointer) * SlabIsEmpty * Is an Slab empty of any allocated space? */ -static bool +bool SlabIsEmpty(MemoryContext context) { SlabContext *slab = castNode(SlabContext, context); @@ -635,7 +599,7 @@ SlabIsEmpty(MemoryContext context) * totals: if not NULL, add stats about this context into *totals. * print_to_stderr: print stats to stderr if true, elog otherwise. */ -static void +void SlabStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, @@ -697,7 +661,7 @@ SlabStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void SlabCheck(MemoryContext context) { int i; @@ -728,6 +692,11 @@ SlabCheck(MemoryContext context) elog(WARNING, "problem in slab %s: number of free chunks %d in block %p does not match freelist %d", name, block->nfree, block, i); + /* make sure the slab pointer correctly points to this context */ + if (block->slab != slab) + elog(WARNING, "problem in slab %s: bogus slab link in block %p", + name, block); + /* reset the bitmap of free chunks for this block */ memset(slab->freechunks, 0, (slab->chunksPerBlock * sizeof(bool))); idx = block->firstFreeChunk; @@ -742,7 +711,7 @@ SlabCheck(MemoryContext context) nfree = 0; while (idx < slab->chunksPerBlock) { - SlabChunk *chunk; + MemoryChunk *chunk; /* count the chunk as free, add it to the bitmap */ nfree++; @@ -750,8 +719,8 @@ SlabCheck(MemoryContext context) /* read index of the next free chunk */ chunk = SlabBlockGetChunk(slab, block, idx); - VALGRIND_MAKE_MEM_DEFINED(SlabChunkGetPointer(chunk), sizeof(int32)); - idx = *(int32 *) SlabChunkGetPointer(chunk); + VALGRIND_MAKE_MEM_DEFINED(MemoryChunkGetPointer(chunk), sizeof(int32)); + idx = *(int32 *) MemoryChunkGetPointer(chunk); } for (j = 0; j < slab->chunksPerBlock; j++) @@ -759,19 +728,19 @@ SlabCheck(MemoryContext context) /* non-zero bit in the bitmap means chunk the chunk is used */ if (!slab->freechunks[j]) { - SlabChunk *chunk = SlabBlockGetChunk(slab, block, j); - - /* chunks have both block and slab pointers, so check both */ - if (chunk->block != block) + MemoryChunk *chunk = SlabBlockGetChunk(slab, block, j); + SlabBlock *chunkblock = (SlabBlock *) MemoryChunkGetBlock(chunk); + + /* + * check the chunk's blockoffset correctly points back to + * the block + */ + if (chunkblock != block) elog(WARNING, "problem in slab %s: bogus block link in block %p, chunk %p", name, block, chunk); - if (chunk->slab != slab) - elog(WARNING, "problem in slab %s: bogus slab link in block %p, chunk %p", - name, block, chunk); - /* there might be sentinel (thanks to alignment) */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) if (!sentinel_ok(chunk, slab->chunkSize)) elog(WARNING, "problem in slab %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); diff --git a/src/include/nodes/memnodes.h b/src/include/nodes/memnodes.h index 16cd56da6d..63d07358cd 100644 --- a/src/include/nodes/memnodes.h +++ b/src/include/nodes/memnodes.h @@ -59,11 +59,12 @@ typedef struct MemoryContextMethods { void *(*alloc) (MemoryContext context, Size size); /* call this free_p in case someone #define's free() */ - void (*free_p) (MemoryContext context, void *pointer); - void *(*realloc) (MemoryContext context, void *pointer, Size size); + void (*free_p) (void *pointer); + void *(*realloc) (void *pointer, Size size); void (*reset) (MemoryContext context); void (*delete_context) (MemoryContext context); - Size (*get_chunk_space) (MemoryContext context, void *pointer); + MemoryContext (*get_chunk_context) (void *pointer); + Size (*get_chunk_space) (void *pointer); bool (*is_empty) (MemoryContext context); void (*stats) (MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, diff --git a/src/include/utils/memutils.h b/src/include/utils/memutils.h index 495d1af201..52bc41ec53 100644 --- a/src/include/utils/memutils.h +++ b/src/include/utils/memutils.h @@ -41,8 +41,11 @@ #define AllocSizeIsValid(size) ((Size) (size) <= MaxAllocSize) +/* Must be less than SIZE_MAX */ #define MaxAllocHugeSize (SIZE_MAX / 2) +#define InvalidAllocSize SIZE_MAX + #define AllocHugeSizeIsValid(size) ((Size) (size) <= MaxAllocHugeSize) @@ -79,6 +82,7 @@ extern void MemoryContextDeleteChildren(MemoryContext context); extern void MemoryContextSetIdentifier(MemoryContext context, const char *id); extern void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent); +extern MemoryContext GetMemoryChunkContext(void *pointer); extern Size GetMemoryChunkSpace(void *pointer); extern MemoryContext MemoryContextGetParent(MemoryContext context); extern bool MemoryContextIsEmpty(MemoryContext context); @@ -98,53 +102,6 @@ extern bool MemoryContextContains(MemoryContext context, void *pointer); #define MemoryContextCopyAndSetIdentifier(cxt, id) \ MemoryContextSetIdentifier(cxt, MemoryContextStrdup(cxt, id)) -/* - * GetMemoryChunkContext - * Given a currently-allocated chunk, determine the context - * it belongs to. - * - * All chunks allocated by any memory context manager are required to be - * preceded by the corresponding MemoryContext stored, without padding, in the - * preceding sizeof(void*) bytes. A currently-allocated chunk must contain a - * backpointer to its owning context. The backpointer is used by pfree() and - * repalloc() to find the context to call. - */ -#ifndef FRONTEND -static inline MemoryContext -GetMemoryChunkContext(void *pointer) -{ - MemoryContext context; - - /* - * Try to detect bogus pointers handed to us, poorly though we can. - * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an - * allocated chunk. - */ - Assert(pointer != NULL); - Assert(pointer == (void *) MAXALIGN(pointer)); - - /* - * OK, it's probably safe to look at the context. - */ - context = *(MemoryContext *) (((char *) pointer) - sizeof(void *)); - - AssertArg(MemoryContextIsValid(context)); - - return context; -} -#endif - -/* - * This routine handles the context-type-independent part of memory - * context creation. It's intended to be called from context-type- - * specific creation routines, and noplace else. - */ -extern void MemoryContextCreate(MemoryContext node, - NodeTag tag, - const MemoryContextMethods *methods, - MemoryContext parent, - const char *name); - extern void HandleLogMemoryContextInterrupt(void); extern void ProcessLogMemoryContextInterrupt(void); diff --git a/src/include/utils/memutils_internal.h b/src/include/utils/memutils_internal.h new file mode 100644 index 0000000000..e10a559726 --- /dev/null +++ b/src/include/utils/memutils_internal.h @@ -0,0 +1,130 @@ +/*------------------------------------------------------------------------- + * + * memutils_internal.h + * This file contains declarations for memory allocation utility + * functions for internal use. + * + * + * Portions Copyright (c) 2022, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/utils/memutils_internal.h + * + *------------------------------------------------------------------------- + */ + +#ifndef MEMUTILS_INTERNAL_H +#define MEMUTILS_INTERNAL_H + +#include "utils/memutils.h" + +extern void *AllocSetAlloc(MemoryContext context, Size size); +extern void AllocSetFree(void *pointer); +extern void *AllocSetRealloc(void *pointer, Size size); +extern void AllocSetReset(MemoryContext context); +extern void AllocSetDelete(MemoryContext context); +extern MemoryContext AllocSetGetChunkContext(void *pointer); +extern Size AllocSetGetChunkSpace(void *pointer); +extern bool AllocSetIsEmpty(MemoryContext context); +extern void AllocSetStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); + +#ifdef MEMORY_CONTEXT_CHECKING +extern void AllocSetCheck(MemoryContext context); +#endif + + +extern void *GenerationAlloc(MemoryContext context, Size size); +extern void GenerationFree(void *pointer); +extern void *GenerationRealloc(void *pointer, Size size); +extern void GenerationReset(MemoryContext context); +extern void GenerationDelete(MemoryContext context); +extern MemoryContext GenerationGetChunkContext(void *pointer); +extern Size GenerationGetChunkSpace(void *pointer); +extern bool GenerationIsEmpty(MemoryContext context); +extern void GenerationStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); + +#ifdef MEMORY_CONTEXT_CHECKING +extern void GenerationCheck(MemoryContext context); +#endif + + +/* + * These functions implement the MemoryContext API for Slab contexts. + */ +extern void *SlabAlloc(MemoryContext context, Size size); +extern void SlabFree(void *pointer); +extern void *SlabRealloc(void *pointer, Size size); +extern void SlabReset(MemoryContext context); +extern void SlabDelete(MemoryContext context); +extern MemoryContext SlabGetChunkContext(void *pointer); +extern Size SlabGetChunkSpace(void *pointer); +extern bool SlabIsEmpty(MemoryContext context); +extern void SlabStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); +#ifdef MEMORY_CONTEXT_CHECKING +extern void SlabCheck(MemoryContext context); +#endif + +/* + * MemoryContextMethodID + * A unique identifier for each MemoryContext implementation which + * indicates the index into the mcxt_methods[] array. See mcxt.c. + */ +typedef enum MemoryContextMethodID +{ + MCTX_ASET_ID, + MCTX_GENERATION_ID, + MCTX_SLAB_ID, +} MemoryContextMethodID; + +/* + * The number of bits that 8-byte memory chunk headers can use to encode the + * MemoryContextMethodID. + */ +#define MEMORY_CONTEXT_METHODID_BITS 3 +/* + * The maximum possible value of for a MemoryContextMethodID and the bitmask + * for binary ANDing out unrelated bits in the 8-byte chunk header. This must + * be set to the maximum value that can be represented by + * MEMORY_CONTEXT_METHODID_BITS bits. + */ +#define MEMORY_CONTEXT_METHODID_MASK 7 + +/* + * This routine handles the context-type-independent part of memory + * context creation. It's intended to be called from context-type- + * specific creation routines, and noplace else. + */ +extern void MemoryContextCreate(MemoryContext node, + NodeTag tag, + MemoryContextMethodID method_id, + MemoryContext parent, + const char *name); + +static inline MemoryContextMethodID +GetMemoryChunkMethodID(void *pointer) +{ + uint64 header; + + /* + * Try to detect bogus pointers handed to us, poorly though we can. + * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an + * allocated chunk. + */ + Assert(pointer != NULL); + Assert(pointer == (void *) MAXALIGN(pointer)); + + header = *((uint64 *) ((char *) pointer - sizeof(uint64))); + + return header & MEMORY_CONTEXT_METHODID_MASK; +} + +#endif /* MEMUTILS_INTERNAL_H */ diff --git a/src/include/utils/memutils_memorychunk.h b/src/include/utils/memutils_memorychunk.h new file mode 100644 index 0000000000..3897dfd508 --- /dev/null +++ b/src/include/utils/memutils_memorychunk.h @@ -0,0 +1,231 @@ +/*------------------------------------------------------------------------- + * + * memutils_memorychunk.h + * Here we define a struct named MemoryChunk which implementations of + * MemoryContexts may use as a header for chunks of memory they allocate. + * + * A MemoryChunk provides a lightweight header which a MemoryContext can use + * to store a reference back to the block the which the given chunk is + * allocated on and also an additional 30-bits to store another value such as + * the size of the allocated chunk. + * + * Although MemoryChunks are used by each of our MemoryContexts, future + * implementations may choose to implement their own method for storing chunk + * headers. The only requirement is that the header end with an 8-byte value + * which the least significant 3-bits of are set to the MemoryContextMethodID + * of the given context. + * + * By default, a MemoryChunk is 8 bytes in size, however when + * MEMORY_CONTEXT_CHECKING is defined the header becomes 16 bytes in size due + * to the additional requested_size field. The MemoryContext may use this + * field for whatever they wish, but it is intended to be used for additional + * checks which are only done in MEMORY_CONTEXT_CHECKING builds. + * + * The MemoryChunk contains a uint64 field named 'hdrmask'. This field is + * used to encode 4 separate pieces of information. Starting with the least + * significant bits of 'hdrmask', the bit space is reserved as follows: + * + * 1. 3-bits to indicate the MemoryContextMethodID as defined by + * MEMORY_CONTEXT_METHODID_MASK + * 2. 1-bit to denote an "external" chunk (see below) + * 3. 30-bits reserved for the MemoryContext to use for anything it + * requires. Most MemoryContext likely want to store the size of the + * chunk here. + * 4. 30-bits for the number of bytes that must be subtracted from the chunk + * to obtain the address of the block that the chunk is stored on. + * + * In some cases, for example when memory allocations become large, it's + * possible fields 3 and 4 above are not large enough to store the values + * required for the chunk. In this case, the MemoryContext can choose to mark + * the chunk as "external" by calling the MemoryChunkSetExternal() function. + * When this is done, fields 3 and 4 are unavailable for use by the + * MemoryContext and it's up to the MemoryContext itself to devise its own + * method for getting the reference to the block. + * + * Interface: + * + * MemoryChunkSetHdrMask: + * Used to set up a non-external MemoryChunk. + * + * MemoryChunkSetHdrMaskExternal: + * Used to set up an externally managed MemoryChunk. + * + * MemoryChunkIsExternal: + * Determine if the given MemoryChunk is externally managed, i.e. + * MemoryChunkSetHdrMaskExternal() was called on the chunk. + * + * MemoryChunkGetValue: + * For non-external chunks, return the stored 30-bit value as it was set + * in the call to MemoryChunkSetHdrMask(). + * + * MemoryChunkGetBlock: + * For non-external chunks, return a pointer to the block as it was set + * in the call to MemoryChunkSetHdrMask(). + * + * Also exports: + * MEMORYCHUNK_MAX_VALUE + * MEMORYCHUNK_MAX_BLOCKOFFSET + * PointerGetMemoryChunk + * MemoryChunkGetPointer + * + * Portions Copyright (c) 2022, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/utils/memutils_memorychunk.h + * + *------------------------------------------------------------------------- + */ + +#ifndef MEMUTILS_MEMORYCHUNK_H +#define MEMUTILS_MEMORYCHUNK_H + +#include "utils/memutils_internal.h" + + /* + * The maximum allowed value that MemoryContexts can store in the value + * field. Must be 1 less than a power of 2. + */ +#define MEMORYCHUNK_MAX_VALUE 0x3FFFFFFF + +/* + * The maximum distance in bytes that a MemoryChunk can be offset from the + * block that is storing the chunk. Must be 1 less than a power of 2. + */ +#define MEMORYCHUNK_MAX_BLOCKOFFSET 0x3FFFFFFF + +/* define the least significant base-0 bit of each portion of the hdrmask */ +#define MEMORYCHUNK_EXTERNAL_BASEBIT MEMORY_CONTEXT_METHODID_BITS +#define MEMORYCHUNK_VALUE_BASEBIT (MEMORYCHUNK_EXTERNAL_BASEBIT + 1) +#define MEMORYCHUNK_BLOCKOFFSET_BASEBIT (MEMORYCHUNK_VALUE_BASEBIT + 30) + +/* A magic number for storing in the free bits of an external chunk */ +#define MEMORYCHUNK_MAGIC (UINT64CONST(0xB1A8DB858EB6EFBA) >> \ + MEMORYCHUNK_VALUE_BASEBIT << \ + MEMORYCHUNK_VALUE_BASEBIT) + +typedef struct MemoryChunk +{ +#ifdef MEMORY_CONTEXT_CHECKING + Size requested_size; +#endif + + /* bitfield for storing details about the chunk */ + uint64 hdrmask; /* must be last */ +} MemoryChunk; + +/* Get the MemoryChunk from the pointer */ +#define PointerGetMemoryChunk(p) ((MemoryChunk *) ((char *) (p) - sizeof(MemoryChunk))) +/* Get the pointer from the MemoryChunk */ +#define MemoryChunkGetPointer(c) ((void *) ((char *) (c) + sizeof(MemoryChunk))) + +/* private macros for making the inline functions below more simple */ +#define HdrMaskIsExternal(hdrmask) \ + ((hdrmask) & (1 << MEMORYCHUNK_EXTERNAL_BASEBIT)) +#define HdrMaskGetValue(hdrmask) \ + (((hdrmask) >> MEMORYCHUNK_VALUE_BASEBIT) & MEMORYCHUNK_MAX_VALUE) + +/* + * We should have used up all the bits here, so the compiler is likely to + * optimize out the & MEMORYCHUNK_MAX_BLOCKOFFSET. + */ +#define HdrMaskBlockOffset(hdrmask) \ + (((hdrmask) >> MEMORYCHUNK_BLOCKOFFSET_BASEBIT) & MEMORYCHUNK_MAX_BLOCKOFFSET) + +/* For external chunks only, check the magic number matches */ +#define HdrMaskCheckMagic(hdrmask) \ + (MEMORYCHUNK_MAGIC == \ + ((hdrmask) >> MEMORYCHUNK_VALUE_BASEBIT << MEMORYCHUNK_VALUE_BASEBIT)) +/* + * MemoryChunkSetHdrMask + * Store the given 'block', 'chunk_size' and 'methodid' in the given + * MemoryChunk. + * + * The number of bytes between 'block' and 'chunk' must be <= + * MEMORYCHUNK_MAX_BLOCKOFFSET. + * 'value' must be <= MEMORYCHUNK_MAX_VALUE. + */ +static inline void +MemoryChunkSetHdrMask(MemoryChunk *chunk, void *block, + Size value, MemoryContextMethodID methodid) +{ + Size blockoffset = (char *) chunk - (char *) block; + + Assert((char *) chunk > (char *) block); + Assert(blockoffset <= MEMORYCHUNK_MAX_BLOCKOFFSET); + Assert(value <= MEMORYCHUNK_MAX_VALUE); + Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK); + + chunk->hdrmask = (blockoffset << MEMORYCHUNK_BLOCKOFFSET_BASEBIT) | + (value << MEMORYCHUNK_VALUE_BASEBIT) | + methodid; +} + +/* + * MemoryChunkSetHdrMaskExternal + * Set 'chunk' as an externally managed chunk. Here we only record the + * MemoryContextMethodID and set the external chunk bit. + */ +static inline void +MemoryChunkSetHdrMaskExternal(MemoryChunk *chunk, + MemoryContextMethodID methodid) +{ + Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK); + + chunk->hdrmask = MEMORYCHUNK_MAGIC | (1 << MEMORYCHUNK_EXTERNAL_BASEBIT) | + methodid; +} + +/* + * MemoryChunkIsExternal + * Return true if 'chunk' is marked as external. + */ +static inline bool +MemoryChunkIsExternal(MemoryChunk *chunk) +{ + /* + * External chunks should always store MEMORYCHUNK_MAGIC in the upper + * portion of the hdrmask. + */ + Assert(!HdrMaskIsExternal(chunk->hdrmask) || + HdrMaskCheckMagic(chunk->hdrmask)); + + return HdrMaskIsExternal(chunk->hdrmask); +} + +/* + * MemoryChunkGetValue + * For non-external chunks, returns the value field as it was set in + * MemoryChunkSetHdrMask. + */ +static inline Size +MemoryChunkGetValue(MemoryChunk *chunk) +{ + Assert(!HdrMaskIsExternal(chunk->hdrmask)); + + return HdrMaskGetValue(chunk->hdrmask); +} + +/* + * MemoryChunkGetBlock + * For non-external chunks, returns the pointer to the block as was set + * in MemoryChunkSetHdrMask. + */ +static inline void * +MemoryChunkGetBlock(MemoryChunk *chunk) +{ + Assert(!HdrMaskIsExternal(chunk->hdrmask)); + + return (void *) ((char *) chunk - HdrMaskBlockOffset(chunk->hdrmask)); +} + +/* cleanup all internal definitions */ +#undef MEMORYCHUNK_EXTERNAL_BASEBIT +#undef MEMORYCHUNK_VALUE_BASEBIT +#undef MEMORYCHUNK_BLOCKOFFSET_BASEBIT +#undef MEMORYCHUNK_MAGIC +#undef HdrMaskIsExternal +#undef HdrMaskGetValue +#undef HdrMaskBlockOffset +#undef HdrMaskCheckMagic + +#endif /* MEMUTILS_MEMORYCHUNK_H */ diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index a4a4e356e5..51a3e719e6 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -57,6 +57,7 @@ AlenState Alias AllocBlock AllocChunk +AllocFreelistLink AllocPointer AllocSet AllocSetContext @@ -1522,12 +1523,14 @@ MemoizeKey MemoizePath MemoizeState MemoizeTuple +MemoryChunk MemoryContext MemoryContextCallback MemoryContextCallbackFunction MemoryContextCounters MemoryContextData MemoryContextMethods +MemoryContextMethodID MemoryStatsPrintFunc MergeAction MergeActionState -- 2.34.1
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-28 11:04  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-08-28 11:04 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Fri, 26 Aug 2022 at 17:16, David Rowley <dgrowleyml@gmail.com> wrote:
> The CFbot just alerted me to the cplusplus check was failing with the
> v5 patch, so here's v6.

I'll try that one again...

David

Attachments:

v7-0001-Improve-performance-of-and-reduce-overheads-of-me.patch (text/plain, 104.4K) download From 90e48eef5709e8cdfb474f8798fa0aef1d0158b1 Mon Sep 17 00:00:00 2001 From: David Rowley <dgrowley@gmail.com> Date: Thu, 9 Jun 2022 20:09:22 +1200 Subject: [PATCH v7] Improve performance of and reduce overheads of memory management Whenever we palloc a chunk of memory, traditionally, we prefix the returned pointer with a pointer to the memory context to which the chunk belongs. This is required so that we're able to easily determine the owning context when performing operations such as pfree() and repalloc(). For the AllocSet context, prior to this commit we additionally prefixed the pointer to the owning context with the size of the chunk. This made the header 16 bytes in size. This 16-byte overhead was required for all AllocSet allocations regardless of the allocation size. For the generation context, the problem was worse; in addition to the pointer to the owning context and chunk size, we also stored a pointer to the owning block so that we could track the number of freed chunks on a block. The slab allocator had a 16-byte chunk header. The changes being made here reduce the chunk header size down to just 8 bytes for all 3 of our memory context types. For small to medium sized allocations, this significantly increases the number of chunks that we can fit on a given block which results in much more efficient use of memory. Additionally, this commit completely changes the rule that pointers to palloc'd memory must be directly prefixed by a pointer to the owning memory context and instead, we now insist that they're directly prefixed by an 8-byte value where the least significant 3-bits are set to a value to indicate which type of memory context the pointer belongs to. Using those 3 bits as an index (known as MemoryContextMethodID) to a new array which stores the methods for each memory context type, we're now able to pass the pointer given to functions such as pfree() and repalloc() to the function specific to that context implementation to allow them to devise their own methods of finding the memory context which owns the given allocated chunk of memory. The reason we're able to reduce the chunk header down to just 8 bytes is because of the way we make use of the remaining 61 bits of the required 8-byte chunk header. Here we also implement a general-purpose MemoryChunk struct which makes use of those 61 remaining bits to allow the storage of a 30-bit value which the MemoryContext is free to use as it pleases, and also the number of bytes which must be subtracted from the chunk to get a reference to the block that the chunk is stored on (also 30 bits). The 1 additional remaining bit is to denote if the chunk is an "external" chunk or not. External here means that the chunk header does not store the 30-bit value or the block offset. The MemoryContext can use these external chunks at any time, but must use them if any of the two 30-bit fields are not large enough for the value(s) that need to be stored in them. When the chunk is marked as external, it is up to the MemoryContext to devise its own means to determine the block offset. Using 3-bits for the MemoryContextMethodID does mean we're limiting ourselves to only having a maximum of 8 different memory context types. We could reduce the bit space for the 30-bit value a little to make way for more than 3 bits, but it seems like it might be better to do that only if we ever need more than 8 context types. This would only be a problem if some future memory context type which does not use MemoryChunk really couldn't give up any of the 61 remaining bits in the chunk header. With this MemoryChunk, each of our 3 memory context types can quickly obtain a reference to the block any given chunk is located on. AllocSet is able to find the context to which the chunk is owned by first obtaining a reference to the block by subtracting the block offset as is stored in the 'hdrmask' field and then referencing the block's 'aset' field. The Generation context uses the same method, but GenerationBlock did not have a field pointing back to the owning context, so one is added by this commit. In aset.c and generation.c, all allocations larger than allocChunkLimit are stored on dedicated blocks. When there's just a single chunk on a block like this, it's easy to find the block from the chunk, we just subtract the size of the block header from the chunk pointer. The size of these chunks is also known as we store the endptr on the block, so we can just subtract the pointer to the allocated memory from that. Because we can easily find the owning block and the size of the chunk for these dedicated blocks, we just always use external chunks for allocation sizes larger than allocChunkLimit. For geneartion.c, this sidesteps the problem of non-external MemoryChunks being unable to represent chunk sizes >= 1GB. This is less of a problem for aset.c as we store the freelist index in the MemoryChunk's spare 30-bit field. we can easily reverse engineer the chunk size from this when needed. Storing this saves AllocSetFree() from having to make a call to AllocSetFreeIndex() to determine which freelist to put the newly freed chunk on. For the slab allocator, this commit adds a new restriction that slab chunks cannot be >= 1GB in size. If there happened to be any users of slab.c which used chunk sizes this large, they really should be using AllocSet instead. Here we also add a restriction that normal non-dedicated blocks cannot be 1GB or larger. It's now not possible to pass a 'maxBlockSize' >= 1GB during the creation of an AllocSet or Generation context. Allocations can still be larger than 1GB, it's just these will always be on dedicated blocks (which are not restricted to 1GB in size). Author: Andres Freund, David Rowley Discussion: https://postgr.es/m/CAApHDvpjauCRXcgcaL6+e3eqecEHoeRm9D-kcbuvBitgPnW=vw@mail.gmail.com --- src/backend/utils/mmgr/README | 60 ++- src/backend/utils/mmgr/aset.c | 507 +++++++++++++---------- src/backend/utils/mmgr/generation.c | 351 ++++++++-------- src/backend/utils/mmgr/mcxt.c | 91 +++- src/backend/utils/mmgr/slab.c | 197 ++++----- src/include/nodes/memnodes.h | 7 +- src/include/utils/memutils.h | 51 +-- src/include/utils/memutils_internal.h | 130 ++++++ src/include/utils/memutils_memorychunk.h | 231 +++++++++++ src/tools/pgindent/typedefs.list | 3 + 10 files changed, 1034 insertions(+), 594 deletions(-) create mode 100644 src/include/utils/memutils_internal.h create mode 100644 src/include/utils/memutils_memorychunk.h diff --git a/src/backend/utils/mmgr/README b/src/backend/utils/mmgr/README index 777481c83d..cd6228b0e2 100644 --- a/src/backend/utils/mmgr/README +++ b/src/backend/utils/mmgr/README @@ -384,35 +384,55 @@ MemoryContext like the parent and child contexts, and the name of the context. This is essentially an abstract superclass, and the behavior is -determined by the "methods" pointer is its virtual function table -(struct MemoryContextMethods). Specific memory context types will use -derived structs having these fields as their first fields. All the +determined by the "methods" pointer which references which set of +MemoryContextMethods are to be used. Specific memory context types will +use derived structs having these fields as their first fields. All the contexts of a specific type will have methods pointers that point to -the same static table of function pointers. +the corresponding element in the mcxt_methods[] array as defined in mcxt.c. While operations like allocating from and resetting a context take the relevant MemoryContext as a parameter, operations like free and realloc are trickier. To make those work, we require all memory context types to produce allocated chunks that are immediately, -without any padding, preceded by a pointer to the corresponding -MemoryContext. +without any padding, preceded by a uint64 value of which the least +significant 3 bits are set to the owning context's MemoryContextMethodID. +This allows the code to determine the correct MemoryContextMethods to +use by looking up the mcxt_methods[] array using the 3 bits as an index +into that array. If a type of allocator needs additional information about its chunks, like e.g. the size of the allocation, that information can in turn -precede the MemoryContext. This means the only overhead implied by -the memory context mechanism is a pointer to its context, so we're not -constraining context-type designers very much. - -Given this, routines like pfree determine their corresponding context -with an operation like (although that is usually encapsulated in -GetMemoryChunkContext()) - - MemoryContext context = *(MemoryContext*) (((char *) pointer) - sizeof(void *)); - -and then invoke the corresponding method for the context - - context->methods->free_p(pointer); - +either be encoded into the remaining 61 bits of the preceding uint64 value +or if more space is required, additional values may be stored directly prior +to the uint64 value. It is up to the context implementation to manage this. + +Given this, routines like pfree can determine which set of +MemoryContextMethods to call the free_p function for by calling +GetMemoryChunkMethodID() and finding the corresponding MemoryContextMethods +in the mcxt_methods array[]. For convenience, the MCXT_METHOD() macro is +provided, making the code as simple as: + +void +pfree(void *pointer) +{ + MCXT_METHOD(pointer, free_p)(pointer); +} + +All of the current memory contexts make use of the MemoryChunk header type +which is defined in memutils_memorychunk.h. This suits all of the existing +context types well as it makes use of the remaining 61-bits of the uint64 +header to efficiently encode the size of the chunk of memory (or freelist +index, in the case of aset.c) and the number of bytes which must be subtracted +from the chunk in order to obtain a reference to the block that the chunk +belongs to. 30 bits are used for each of these. If more than 30 bits are +required then the memory context must manage that itself. This can be done by +calling the MemoryChunkSetHdrMaskExternal() function on the given chunk. +Currently, each memory context type stores large allocations on dedicated +blocks (which always contain only a single chunk). For these, finding the +block is simple as we know that the chunk must be the first on the given +block, so the block is always at a fixed offset to the chunk. For these, +finding the size of the chunk is also simple as the block always stores an +endptr which we can use to calculate the size of the chunk. More Control Over aset.c Behavior --------------------------------- diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index ec3e264a73..285a908e4a 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -49,6 +49,8 @@ #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" /*-------------------- * Chunk freelist k holds chunks of size 1 << (k + ALLOC_MINBITS), @@ -66,7 +68,9 @@ * CAUTION: ALLOC_MINBITS must be large enough so that * 1<<ALLOC_MINBITS is at least MAXALIGN, * or we may fail to align the smallest chunks adequately. - * 8-byte alignment is enough on all currently known machines. + * 8-byte alignment is enough on all currently known machines. This 8-byte + * minimum also allows us to store a pointer to the next freelist item within + * the chunk of memory itself. * * With the current parameters, request sizes up to 8K are treated as chunks, * larger requests go into dedicated blocks. Change ALLOCSET_NUM_FREELISTS @@ -98,10 +102,9 @@ */ #define ALLOC_BLOCKHDRSZ MAXALIGN(sizeof(AllocBlockData)) -#define ALLOC_CHUNKHDRSZ sizeof(struct AllocChunkData) +#define ALLOC_CHUNKHDRSZ sizeof(MemoryChunk) typedef struct AllocBlockData *AllocBlock; /* forward reference */ -typedef struct AllocChunkData *AllocChunk; /* * AllocPointer @@ -109,6 +112,33 @@ typedef struct AllocChunkData *AllocChunk; */ typedef void *AllocPointer; +/* + * AllocFreelistLink + * When pfreeing memory, if we maintain a freelist for the given chunk's + * size then we use a AllocFreelistLink to point to the current item in + * the AllocSetContext's freelist and then set the given freelist element + * to point to the chunk being freed. + */ +typedef struct AllocFreelistLink +{ + MemoryChunk *next; +} AllocFreelistLink; + +/* + * Obtain a AllocFreelistLink for the given chunk. Allocation sizes are + * always at least sizeof(AllocFreelistLink), so we reuse the pointer's memory + * itself to store the freelist link. To make it less likely that any write + * after pfree() bugs corrupt this, we put the link at the very end of the + * allocated chunk. + */ +#define GetFreeListLink(chkptr, chksz) \ + (AllocFreelistLink *) ((char *) (chkptr) + ALLOC_CHUNKHDRSZ + \ + (chksz) - sizeof(AllocFreelistLink)) + +/* Determine the size of the chunk based on the freelist index */ +#define GetChunkSizeFromFreelistIdx(fidx) \ + ((((Size) 1) << ALLOC_MINBITS) << (fidx)) + /* * AllocSetContext is our standard implementation of MemoryContext. * @@ -123,7 +153,7 @@ typedef struct AllocSetContext MemoryContextData header; /* Standard memory-context fields */ /* Info about storage allocated in this context: */ AllocBlock blocks; /* head of list of blocks in this set */ - AllocChunk freelist[ALLOCSET_NUM_FREELISTS]; /* free chunk lists */ + MemoryChunk *freelist[ALLOCSET_NUM_FREELISTS]; /* free chunk lists */ /* Allocation parameters for this context: */ Size initBlockSize; /* initial block size */ Size maxBlockSize; /* maximum block size */ @@ -139,8 +169,8 @@ typedef AllocSetContext *AllocSet; /* * AllocBlock * An AllocBlock is the unit of memory that is obtained by aset.c - * from malloc(). It contains one or more AllocChunks, which are - * the units requested by palloc() and freed by pfree(). AllocChunks + * from malloc(). It contains one or more MemoryChunks, which are + * the units requested by palloc() and freed by pfree(). MemoryChunks * cannot be returned to malloc() individually, instead they are put * on freelists by pfree() and re-used by the next palloc() that has * a matching request size. @@ -158,48 +188,12 @@ typedef struct AllocBlockData } AllocBlockData; /* - * AllocChunk - * The prefix of each piece of memory in an AllocBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "aset" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). We simplify matters for this - * module by requiring sizeof(AllocChunkData) to be maxaligned, and then - * we can ensure things work by adding any required alignment padding before - * the "aset" field. There is a static assertion below that the alignment - * is done correctly. - */ -typedef struct AllocChunkData -{ - /* size is always the size of the usable space in the chunk */ - Size size; -#ifdef MEMORY_CONTEXT_CHECKING - /* when debugging memory usage, also store actual requested size */ - /* this is zero in a free chunk */ - Size requested_size; - -#define ALLOCCHUNK_RAWSIZE (SIZEOF_SIZE_T * 2 + SIZEOF_VOID_P) -#else -#define ALLOCCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P) -#endif /* MEMORY_CONTEXT_CHECKING */ - - /* ensure proper alignment by adding padding if needed */ -#if (ALLOCCHUNK_RAWSIZE % MAXIMUM_ALIGNOF) != 0 - char padding[MAXIMUM_ALIGNOF - ALLOCCHUNK_RAWSIZE % MAXIMUM_ALIGNOF]; -#endif - - /* aset is the owning aset if allocated, or the freelist link if free */ - void *aset; - /* there must not be any padding to reach a MAXALIGN boundary here! */ -} AllocChunkData; - -/* - * Only the "aset" field should be accessed outside this module. + * Only the "hdrmask" field should be accessed outside this module. * We keep the rest of an allocated chunk's header marked NOACCESS when using * valgrind. But note that chunk headers that are in a freelist are kept * accessible, for simplicity. */ -#define ALLOCCHUNK_PRIVATE_LEN offsetof(AllocChunkData, aset) +#define ALLOCCHUNK_PRIVATE_LEN offsetof(MemoryChunk, hdrmask) /* * AllocPointerIsValid @@ -213,10 +207,12 @@ typedef struct AllocChunkData */ #define AllocSetIsValid(set) PointerIsValid(set) -#define AllocPointerGetChunk(ptr) \ - ((AllocChunk)(((char *)(ptr)) - ALLOC_CHUNKHDRSZ)) -#define AllocChunkGetPointer(chk) \ - ((AllocPointer)(((char *)(chk)) + ALLOC_CHUNKHDRSZ)) +/* + * We always store external chunks on a dedicated block. This makes fetching + * the block from an external chunk easy since it's always the first and only + * chunk on the block. + */ +#define ExternalChunkGetBlock(chunk) (AllocBlock) ((char *) chunk - ALLOC_BLOCKHDRSZ) /* * Rather than repeatedly creating and deleting memory contexts, we keep some @@ -260,42 +256,6 @@ static AllocSetFreeList context_freelists[2] = } }; -/* - * These functions implement the MemoryContext API for AllocSet contexts. - */ -static void *AllocSetAlloc(MemoryContext context, Size size); -static void AllocSetFree(MemoryContext context, void *pointer); -static void *AllocSetRealloc(MemoryContext context, void *pointer, Size size); -static void AllocSetReset(MemoryContext context); -static void AllocSetDelete(MemoryContext context); -static Size AllocSetGetChunkSpace(MemoryContext context, void *pointer); -static bool AllocSetIsEmpty(MemoryContext context); -static void AllocSetStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); - -#ifdef MEMORY_CONTEXT_CHECKING -static void AllocSetCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for AllocSet contexts. - */ -static const MemoryContextMethods AllocSetMethods = { - AllocSetAlloc, - AllocSetFree, - AllocSetRealloc, - AllocSetReset, - AllocSetDelete, - AllocSetGetChunkSpace, - AllocSetIsEmpty, - AllocSetStats -#ifdef MEMORY_CONTEXT_CHECKING - ,AllocSetCheck -#endif -}; - /* ---------- * AllocSetFreeIndex - @@ -387,18 +347,24 @@ AllocSetContextCreateInternal(MemoryContext parent, AllocSet set; AllocBlock block; - /* Assert we padded AllocChunkData properly */ + /* ensure MemoryChunk's size is properly maxaligned */ StaticAssertStmt(ALLOC_CHUNKHDRSZ == MAXALIGN(ALLOC_CHUNKHDRSZ), - "sizeof(AllocChunkData) is not maxaligned"); - StaticAssertStmt(offsetof(AllocChunkData, aset) + sizeof(MemoryContext) == - ALLOC_CHUNKHDRSZ, - "padding calculation in AllocChunkData is wrong"); + "sizeof(MemoryChunk) is not maxaligned"); + /* check we have enough space to store the freelist link */ + StaticAssertStmt(sizeof(AllocFreelistLink) <= (1 << ALLOC_MINBITS), + "sizeof(AllocFreelistLink) larger than minimum allocation size"); /* * First, validate allocation parameters. Once these were regular runtime * test and elog's, but in practice Asserts seem sufficient because nobody * varies their parameters at runtime. We somewhat arbitrarily enforce a - * minimum 1K block size. + * minimum 1K block size. We restrict the maximum block size to + * MEMORYCHUNK_MAX_BLOCKOFFSET as MemoryChunks are limited to this in + * regards to addressing the offset between the chunk and the block that + * the chunk is stored on. We would be unable to store the offset between + * the chunk and block for any chunks that were beyond + * MEMORYCHUNK_MAX_BLOCKOFFSET bytes into the block if the block was to be + * larger than this. */ Assert(initBlockSize == MAXALIGN(initBlockSize) && initBlockSize >= 1024); @@ -409,6 +375,7 @@ AllocSetContextCreateInternal(MemoryContext parent, (minContextSize == MAXALIGN(minContextSize) && minContextSize >= 1024 && minContextSize <= maxBlockSize)); + Assert(maxBlockSize <= MEMORYCHUNK_MAX_BLOCKOFFSET); /* * Check whether the parameters match either available freelist. We do @@ -443,7 +410,7 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Reinitialize its header, installing correct name and parent */ MemoryContextCreate((MemoryContext) set, T_AllocSetContext, - &AllocSetMethods, + MCTX_ASET_ID, parent, name); @@ -519,7 +486,8 @@ AllocSetContextCreateInternal(MemoryContext parent, * * We have to have allocChunkLimit a power of two, because the requested * and actually-allocated sizes of any chunk must be on the same side of - * the limit, else we get confused about whether the chunk is "big". + * the limit, else we get confused about whether the chunk is on a + * dedicated block. * * Also, allocChunkLimit must not exceed ALLOCSET_SEPARATE_THRESHOLD. */ @@ -534,7 +502,7 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) set, T_AllocSetContext, - &AllocSetMethods, + MCTX_ASET_ID, parent, name); @@ -555,7 +523,7 @@ AllocSetContextCreateInternal(MemoryContext parent, * thrash malloc() when a context is repeatedly reset after small allocations, * which is typical behavior for per-tuple contexts. */ -static void +void AllocSetReset(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -623,7 +591,7 @@ AllocSetReset(MemoryContext context) * * Unlike AllocSetReset, this *must* free all resources of the set. */ -static void +void AllocSetDelete(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -717,12 +685,12 @@ AllocSetDelete(MemoryContext context) * is marked, as mcxt.c will set it to UNDEFINED. In some paths we will * return space that is marked NOACCESS - AllocSetRealloc has to beware! */ -static void * +void * AllocSetAlloc(MemoryContext context, Size size) { AllocSet set = (AllocSet) context; AllocBlock block; - AllocChunk chunk; + MemoryChunk *chunk; int fidx; Size chunk_size; Size blksize; @@ -746,18 +714,20 @@ AllocSetAlloc(MemoryContext context, Size size) block->aset = set; block->freeptr = block->endptr = ((char *) block) + blksize; - chunk = (AllocChunk) (((char *) block) + ALLOC_BLOCKHDRSZ); - chunk->aset = set; - chunk->size = chunk_size; + chunk = (MemoryChunk *) (((char *) block) + ALLOC_BLOCKHDRSZ); + + /* mark the MemoryChunk as externally managed */ + MemoryChunkSetHdrMaskExternal(chunk, MCTX_ASET_ID); + #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk_size) - set_sentinel(AllocChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* @@ -780,13 +750,13 @@ AllocSetAlloc(MemoryContext context, Size size) } /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -799,37 +769,43 @@ AllocSetAlloc(MemoryContext context, Size size) chunk = set->freelist[fidx]; if (chunk != NULL) { - Assert(chunk->size >= size); + AllocFreelistLink *link; - set->freelist[fidx] = (AllocChunk) chunk->aset; + Assert(fidx == MemoryChunkGetValue(chunk)); - chunk->aset = (void *) set; + chunk_size = GetChunkSizeFromFreelistIdx(fidx); + link = GetFreeListLink(chunk, chunk_size); + + /* pop this chunk off the freelist */ + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + set->freelist[fidx] = link->next; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(AllocChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, - chunk->size - size); + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, + chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * Choose the actual chunk size to allocate. */ - chunk_size = (1 << ALLOC_MINBITS) << fidx; + chunk_size = GetChunkSizeFromFreelistIdx(fidx); Assert(chunk_size >= size); /* @@ -856,6 +832,7 @@ AllocSetAlloc(MemoryContext context, Size size) */ while (availspace >= ((1 << ALLOC_MINBITS) + ALLOC_CHUNKHDRSZ)) { + AllocFreelistLink *link; Size availchunk = availspace - ALLOC_CHUNKHDRSZ; int a_fidx = AllocSetFreeIndex(availchunk); @@ -864,29 +841,34 @@ AllocSetAlloc(MemoryContext context, Size size) * freelist than the one we need to put this chunk on. The * exception is when availchunk is exactly a power of 2. */ - if (availchunk != ((Size) 1 << (a_fidx + ALLOC_MINBITS))) + if (availchunk != GetChunkSizeFromFreelistIdx(a_fidx)) { a_fidx--; Assert(a_fidx >= 0); - availchunk = ((Size) 1 << (a_fidx + ALLOC_MINBITS)); + availchunk = GetChunkSizeFromFreelistIdx(a_fidx); } - chunk = (AllocChunk) (block->freeptr); + chunk = (MemoryChunk *) (block->freeptr); /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, ALLOC_CHUNKHDRSZ); - block->freeptr += (availchunk + ALLOC_CHUNKHDRSZ); availspace -= (availchunk + ALLOC_CHUNKHDRSZ); - chunk->size = availchunk; + /* store the freelist index in the value field */ + MemoryChunkSetHdrMask(chunk, block, a_fidx, MCTX_ASET_ID); #ifdef MEMORY_CONTEXT_CHECKING - chunk->requested_size = 0; /* mark it free */ + chunk->requested_size = InvalidAllocSize; /* mark it free */ #endif - chunk->aset = (void *) set->freelist[a_fidx]; + /* push this chunk onto the freelist */ + link = GetFreeListLink(chunk, availchunk); + + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + link->next = set->freelist[a_fidx]; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); + set->freelist[a_fidx] = chunk; } - /* Mark that we need to create a new block */ block = NULL; } @@ -954,7 +936,7 @@ AllocSetAlloc(MemoryContext context, Size size) /* * OK, do the allocation */ - chunk = (AllocChunk) (block->freeptr); + chunk = (MemoryChunk *) (block->freeptr); /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, ALLOC_CHUNKHDRSZ); @@ -962,67 +944,68 @@ AllocSetAlloc(MemoryContext context, Size size) block->freeptr += (chunk_size + ALLOC_CHUNKHDRSZ); Assert(block->freeptr <= block->endptr); - chunk->aset = (void *) set; - chunk->size = chunk_size; + /* store the freelist index in the value field */ + MemoryChunkSetHdrMask(chunk, block, fidx, MCTX_ASET_ID); + #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(AllocChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * AllocSetFree * Frees allocated memory; memory is removed from the set. */ -static void -AllocSetFree(MemoryContext context, void *pointer) +void +AllocSetFree(void *pointer) { - AllocSet set = (AllocSet) context; - AllocChunk chunk = AllocPointerGetChunk(pointer); + AllocSet set; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); + if (MemoryChunkIsExternal(chunk)) + { + + AllocBlock block = ExternalChunkGetBlock(chunk); + + set = block->aset; + #ifdef MEMORY_CONTEXT_CHECKING - /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunk->size) - if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", - set->header.name, chunk); + { + Size chunk_size = block->endptr - (char *) pointer; + + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < chunk_size) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); + } #endif - if (chunk->size > set->allocChunkLimit) - { - /* - * Big chunks are certain to have been allocated as single-chunk - * blocks. Just unlink that block and return it to malloc(). - */ - AllocBlock block = (AllocBlock) (((char *) chunk) - ALLOC_BLOCKHDRSZ); /* - * Try to verify that we have a sane block pointer: it should - * reference the correct aset, and freeptr and endptr should point - * just past the chunk. + * Try to verify that we have a sane block pointer, the freeptr should + * match the endptr. */ - if (block->aset != set || - block->freeptr != block->endptr || - block->freeptr != ((char *) block) + - (chunk->size + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) + if (block->freeptr != block->endptr) elog(ERROR, "could not find block containing chunk %p", chunk); /* OK, remove block from aset's list and free it */ @@ -1033,7 +1016,7 @@ AllocSetFree(MemoryContext context, void *pointer) if (block->next) block->next->prev = block->prev; - context->mem_allocated -= block->endptr - ((char *) block); + set->header.mem_allocated -= block->endptr - ((char *) block); #ifdef CLOBBER_FREED_MEMORY wipe_mem(block, block->freeptr - ((char *) block)); @@ -1042,20 +1025,39 @@ AllocSetFree(MemoryContext context, void *pointer) } else { - /* Normal case, put the chunk into appropriate freelist */ - int fidx = AllocSetFreeIndex(chunk->size); + int fidx = MemoryChunkGetValue(chunk); + AllocBlock block = MemoryChunkGetBlock(chunk); + Size chunk_size = GetChunkSizeFromFreelistIdx(fidx); + AllocFreelistLink *link = GetFreeListLink(chunk, chunk_size); - chunk->aset = (void *) set->freelist[fidx]; + set = block->aset; + +#ifdef MEMORY_CONTEXT_CHECKING + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < chunk_size) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); +#endif #ifdef CLOBBER_FREED_MEMORY - wipe_mem(pointer, chunk->size); + wipe_mem(pointer, chunk_size); #endif + /* Normal case, put the chunk into appropriate freelist */ + /* push this chunk onto the top of the freelist for this chunk size */ + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + link->next = set->freelist[fidx]; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); + set->freelist[fidx] = chunk; #ifdef MEMORY_CONTEXT_CHECKING - /* Reset requested_size to 0 in chunks that are on freelist */ - chunk->requested_size = 0; + + /* + * Reset requested_size to InvalidAllocSize in chunks that are on + * freelist. + */ + chunk->requested_size = InvalidAllocSize; #endif - set->freelist[fidx] = chunk; } } @@ -1071,57 +1073,48 @@ AllocSetFree(MemoryContext context, void *pointer) * (In principle, we could use VALGRIND_GET_VBITS() to rediscover the old * request size.) */ -static void * -AllocSetRealloc(MemoryContext context, void *pointer, Size size) +void * +AllocSetRealloc(void *pointer, Size size) { - AllocSet set = (AllocSet) context; - AllocChunk chunk = AllocPointerGetChunk(pointer); + AllocBlock block; + AllocSet set; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); Size oldsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - oldsize = chunk->size; - -#ifdef MEMORY_CONTEXT_CHECKING - /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < oldsize) - if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", - set->header.name, chunk); -#endif - - if (oldsize > set->allocChunkLimit) + if (MemoryChunkIsExternal(chunk)) { /* * The chunk must have been allocated as a single-chunk block. Use * realloc() to make the containing block bigger, or smaller, with * minimum space wastage. */ - AllocBlock block = (AllocBlock) (((char *) chunk) - ALLOC_BLOCKHDRSZ); Size chksize; Size blksize; Size oldblksize; + block = ExternalChunkGetBlock(chunk); + oldsize = block->endptr - (char *) pointer; + set = block->aset; + +#ifdef MEMORY_CONTEXT_CHECKING + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < oldsize) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); +#endif + /* - * Try to verify that we have a sane block pointer: it should - * reference the correct aset, and freeptr and endptr should point - * just past the chunk. + * Try to verify that we have a sane block pointer, the freeptr should + * match the endptr. */ - if (block->aset != set || - block->freeptr != block->endptr || - block->freeptr != ((char *) block) + - (oldsize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) + if (block->freeptr != block->endptr) elog(ERROR, "could not find block containing chunk %p", chunk); - /* - * Even if the new request is less than set->allocChunkLimit, we stick - * with the single-chunk block approach. Therefore we need - * chunk->size to be bigger than set->allocChunkLimit, so we don't get - * confused about the chunk's status in future calls. - */ - chksize = Max(size, set->allocChunkLimit + 1); - chksize = MAXALIGN(chksize); + chksize = MAXALIGN(size); /* Do the realloc */ blksize = chksize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ; @@ -1136,21 +1129,20 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) } /* updated separately, not to underflow when (oldblksize > blksize) */ - context->mem_allocated -= oldblksize; - context->mem_allocated += blksize; + set->header.mem_allocated -= oldblksize; + set->header.mem_allocated += blksize; block->freeptr = block->endptr = ((char *) block) + blksize; /* Update pointers since block has likely been moved */ - chunk = (AllocChunk) (((char *) block) + ALLOC_BLOCKHDRSZ); - pointer = AllocChunkGetPointer(chunk); + chunk = (MemoryChunk *) (((char *) block) + ALLOC_BLOCKHDRSZ); + pointer = MemoryChunkGetPointer(chunk); if (block->prev) block->prev->next = block; else set->blocks = block; if (block->next) block->next->prev = block; - chunk->size = chksize; #ifdef MEMORY_CONTEXT_CHECKING #ifdef RANDOMIZE_ALLOCATED_MEMORY @@ -1172,9 +1164,8 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) #endif chunk->requested_size = size; - /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) + if (size < chksize) set_sentinel(pointer, size); #else /* !MEMORY_CONTEXT_CHECKING */ @@ -1195,12 +1186,24 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) return pointer; } + block = MemoryChunkGetBlock(chunk); + oldsize = GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)); + set = block->aset; + +#ifdef MEMORY_CONTEXT_CHECKING + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < oldsize) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); +#endif + /* * Chunk sizes are aligned to power of 2 in AllocSetAlloc(). Maybe the * allocated area already is >= the new size. (In particular, we will * fall out here if the requested size is a decrease.) */ - else if (oldsize >= size) + if (oldsize >= size) { #ifdef MEMORY_CONTEXT_CHECKING Size oldrequest = chunk->requested_size; @@ -1289,34 +1292,59 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) memcpy(newPointer, pointer, oldsize); /* free old chunk */ - AllocSetFree((MemoryContext) set, pointer); + AllocSetFree(pointer); return newPointer; } } +/* + * AllocSetGetChunkContext + * Return the MemoryContext that 'pointer' belongs to. + */ +MemoryContext +AllocSetGetChunkContext(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + AllocBlock block; + AllocSet set; + + if (MemoryChunkIsExternal(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (AllocBlock) MemoryChunkGetBlock(chunk); + + set = block->aset; + + return &set->header; +} + /* * AllocSetGetChunkSpace * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -AllocSetGetChunkSpace(MemoryContext context, void *pointer) +Size +AllocSetGetChunkSpace(void *pointer) { - AllocChunk chunk = AllocPointerGetChunk(pointer); - Size result; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); - VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - result = chunk->size + ALLOC_CHUNKHDRSZ; - VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return result; + if (MemoryChunkIsExternal(chunk)) + { + AllocBlock block = ExternalChunkGetBlock(chunk); + + return block->endptr - (char *) chunk; + } + + return GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)) + + ALLOC_CHUNKHDRSZ; } /* * AllocSetIsEmpty * Is an allocset empty of any allocated space? */ -static bool +bool AllocSetIsEmpty(MemoryContext context) { /* @@ -1339,7 +1367,7 @@ AllocSetIsEmpty(MemoryContext context) * totals: if not NULL, add stats about this context into *totals. * print_to_stderr: print stats to stderr if true, elog otherwise. */ -static void +void AllocSetStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr) @@ -1363,13 +1391,21 @@ AllocSetStats(MemoryContext context, } for (fidx = 0; fidx < ALLOCSET_NUM_FREELISTS; fidx++) { - AllocChunk chunk; + MemoryChunk *chunk = set->freelist[fidx]; - for (chunk = set->freelist[fidx]; chunk != NULL; - chunk = (AllocChunk) chunk->aset) + while (chunk != NULL) { + Size chksz = GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)); + AllocFreelistLink *link = GetFreeListLink(chunk, chksz); + + Assert(GetChunkSizeFromFreelistIdx(fidx) == chksz); + freechunks++; - freespace += chunk->size + ALLOC_CHUNKHDRSZ; + freespace += chksz + ALLOC_CHUNKHDRSZ; + + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + chunk = link->next; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); } } @@ -1404,7 +1440,7 @@ AllocSetStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void AllocSetCheck(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -1421,6 +1457,7 @@ AllocSetCheck(MemoryContext context) long blk_used = block->freeptr - bpoz; long blk_data = 0; long nchunks = 0; + bool has_external_chunk = false; if (set->keeper == block) total_allocated += block->endptr - ((char *) set); @@ -1452,20 +1489,31 @@ AllocSetCheck(MemoryContext context) */ while (bpoz < block->freeptr) { - AllocChunk chunk = (AllocChunk) bpoz; + MemoryChunk *chunk = (MemoryChunk *) bpoz; + AllocBlock chunkblock; Size chsize, dsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - chsize = chunk->size; /* aligned chunk size */ + if (MemoryChunkIsExternal(chunk)) + { + chsize = block->endptr - (char *) MemoryChunkGetPointer(chunk); /* aligned chunk size */ + chunkblock = ExternalChunkGetBlock(chunk); + has_external_chunk = true; + } + else + { + chsize = GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)); /* aligned chunk size */ + chunkblock = (AllocBlock) MemoryChunkGetBlock(chunk); + } dsize = chunk->requested_size; /* real data */ /* * Check chunk size */ - if (dsize > chsize) + if (dsize != InvalidAllocSize && dsize > chsize) elog(WARNING, "problem in alloc set %s: req size > alloc size for chunk %p in block %p", name, chunk, block); if (chsize < (1 << ALLOC_MINBITS)) @@ -1478,20 +1526,15 @@ AllocSetCheck(MemoryContext context) elog(WARNING, "problem in alloc set %s: bad single-chunk %p in block %p", name, chunk, block); - /* - * If chunk is allocated, check for correct aset pointer. (If it's - * free, the aset is the freelist pointer, which we can't check as - * easily...) Note this is an incomplete test, since palloc(0) - * produces an allocated chunk with requested_size == 0. - */ - if (dsize > 0 && chunk->aset != (void *) set) - elog(WARNING, "problem in alloc set %s: bogus aset link in block %p, chunk %p", - name, block, chunk); + /* Check the block offset correctly matches this block */ + if (block != chunkblock) + elog(WARNING, "problem in alloc set %s: bad block offset for chunk %p in block %p", + name, chunk, block); /* * Check for overwrite of padding space in an allocated chunk. */ - if (chunk->aset == (void *) set && dsize < chsize && + if (dsize != InvalidAllocSize && dsize < chsize && !sentinel_ok(chunk, ALLOC_CHUNKHDRSZ + dsize)) elog(WARNING, "problem in alloc set %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); @@ -1500,7 +1543,7 @@ AllocSetCheck(MemoryContext context) * If chunk is allocated, disallow external access to private part * of chunk header. */ - if (chunk->aset == (void *) set) + if (dsize != InvalidAllocSize) VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); blk_data += chsize; @@ -1512,6 +1555,10 @@ AllocSetCheck(MemoryContext context) if ((blk_data + (nchunks * ALLOC_CHUNKHDRSZ)) != blk_used) elog(WARNING, "problem in alloc set %s: found inconsistent memory block %p", name, block); + + if (has_external_chunk && nchunks > 1) + elog(WARNING, "problem in alloc set %s: external chunk on non-dedicated block %p", + name, block); } Assert(total_allocated == context->mem_allocated); diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index e530e272e0..eac3079823 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -39,15 +39,16 @@ #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" #define Generation_BLOCKHDRSZ MAXALIGN(sizeof(GenerationBlock)) -#define Generation_CHUNKHDRSZ sizeof(GenerationChunk) +#define Generation_CHUNKHDRSZ sizeof(MemoryChunk) #define Generation_CHUNK_FRACTION 8 typedef struct GenerationBlock GenerationBlock; /* forward reference */ -typedef struct GenerationChunk GenerationChunk; typedef void *GenerationPointer; @@ -89,6 +90,7 @@ typedef struct GenerationContext struct GenerationBlock { dlist_node node; /* doubly-linked list of blocks */ + GenerationContext *context; /* pointer back to the owning context */ Size blksize; /* allocated size of this block */ int nchunks; /* number of chunks in the block */ int nfree; /* number of free chunks */ @@ -97,104 +99,36 @@ struct GenerationBlock }; /* - * GenerationChunk - * The prefix of each piece of memory in a GenerationBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "context" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). We simplify matters for this - * module by requiring sizeof(GenerationChunk) to be maxaligned, and then - * we can ensure things work by adding any required alignment padding before - * the pointer fields. There is a static assertion below that the alignment - * is done correctly. - */ -struct GenerationChunk -{ - /* size is always the size of the usable space in the chunk */ - Size size; -#ifdef MEMORY_CONTEXT_CHECKING - /* when debugging memory usage, also store actual requested size */ - /* this is zero in a free chunk */ - Size requested_size; - -#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T * 2 + SIZEOF_VOID_P * 2) -#else -#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P * 2) -#endif /* MEMORY_CONTEXT_CHECKING */ - - /* ensure proper alignment by adding padding if needed */ -#if (GENERATIONCHUNK_RAWSIZE % MAXIMUM_ALIGNOF) != 0 - char padding[MAXIMUM_ALIGNOF - GENERATIONCHUNK_RAWSIZE % MAXIMUM_ALIGNOF]; -#endif - - GenerationBlock *block; /* block owning this chunk */ - GenerationContext *context; /* owning context, or NULL if freed chunk */ - /* there must not be any padding to reach a MAXALIGN boundary here! */ -}; - -/* - * Only the "context" field should be accessed outside this module. + * Only the "hdrmask" field should be accessed outside this module. * We keep the rest of an allocated chunk's header marked NOACCESS when using * valgrind. But note that freed chunk headers are kept accessible, for * simplicity. */ -#define GENERATIONCHUNK_PRIVATE_LEN offsetof(GenerationChunk, context) - +#define GENERATIONCHUNK_PRIVATE_LEN offsetof(MemoryChunk, hdrmask) /* * GenerationIsValid * True iff set is valid allocation set. */ #define GenerationIsValid(set) PointerIsValid(set) -#define GenerationPointerGetChunk(ptr) \ - ((GenerationChunk *)(((char *)(ptr)) - Generation_CHUNKHDRSZ)) -#define GenerationChunkGetPointer(chk) \ - ((GenerationPointer *)(((char *)(chk)) + Generation_CHUNKHDRSZ)) +/* + * We always store external chunks on a dedicated block. This makes fetching + * the block from an external chunk easy since it's always the first and only + * chunk on the block. + */ +#define ExternalChunkGetBlock(chunk) \ + (GenerationBlock *) ((char *) chunk - Generation_BLOCKHDRSZ) /* Inlined helper functions */ -static inline void GenerationBlockInit(GenerationBlock *block, Size blksize); +static inline void GenerationBlockInit(GenerationContext *context, + GenerationBlock *block, + Size blksize); static inline bool GenerationBlockIsEmpty(GenerationBlock *block); static inline void GenerationBlockMarkEmpty(GenerationBlock *block); static inline Size GenerationBlockFreeBytes(GenerationBlock *block); static inline void GenerationBlockFree(GenerationContext *set, GenerationBlock *block); -/* - * These functions implement the MemoryContext API for Generation contexts. - */ -static void *GenerationAlloc(MemoryContext context, Size size); -static void GenerationFree(MemoryContext context, void *pointer); -static void *GenerationRealloc(MemoryContext context, void *pointer, Size size); -static void GenerationReset(MemoryContext context); -static void GenerationDelete(MemoryContext context); -static Size GenerationGetChunkSpace(MemoryContext context, void *pointer); -static bool GenerationIsEmpty(MemoryContext context); -static void GenerationStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); - -#ifdef MEMORY_CONTEXT_CHECKING -static void GenerationCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for Generation contexts. - */ -static const MemoryContextMethods GenerationMethods = { - GenerationAlloc, - GenerationFree, - GenerationRealloc, - GenerationReset, - GenerationDelete, - GenerationGetChunkSpace, - GenerationIsEmpty, - GenerationStats -#ifdef MEMORY_CONTEXT_CHECKING - ,GenerationCheck -#endif -}; - /* * Public routines @@ -223,17 +157,20 @@ GenerationContextCreate(MemoryContext parent, GenerationContext *set; GenerationBlock *block; - /* Assert we padded GenerationChunk properly */ + /* ensure MemoryChunk's size is properly maxaligned */ StaticAssertStmt(Generation_CHUNKHDRSZ == MAXALIGN(Generation_CHUNKHDRSZ), - "sizeof(GenerationChunk) is not maxaligned"); - StaticAssertStmt(offsetof(GenerationChunk, context) + sizeof(MemoryContext) == - Generation_CHUNKHDRSZ, - "padding calculation in GenerationChunk is wrong"); + "sizeof(MemoryChunk) is not maxaligned"); /* * First, validate allocation parameters. Asserts seem sufficient because * nobody varies their parameters at runtime. We somewhat arbitrarily - * enforce a minimum 1K block size. + * enforce a minimum 1K block size. We restrict the maximum block size to + * MEMORYCHUNK_MAX_BLOCKOFFSET as MemoryChunks are limited to this in + * regards to addressing the offset between the chunk and the block that + * the chunk is stored on. We would be unable to store the offset between + * the chunk and block for any chunks that were beyond + * MEMORYCHUNK_MAX_BLOCKOFFSET bytes into the block if the block was to be + * larger than this. */ Assert(initBlockSize == MAXALIGN(initBlockSize) && initBlockSize >= 1024); @@ -244,6 +181,7 @@ GenerationContextCreate(MemoryContext parent, (minContextSize == MAXALIGN(minContextSize) && minContextSize >= 1024 && minContextSize <= maxBlockSize)); + Assert(maxBlockSize <= MEMORYCHUNK_MAX_BLOCKOFFSET); /* Determine size of initial block */ allocSize = MAXALIGN(sizeof(GenerationContext)) + @@ -278,7 +216,7 @@ GenerationContextCreate(MemoryContext parent, block = (GenerationBlock *) (((char *) set) + MAXALIGN(sizeof(GenerationContext))); /* determine the block size and initialize it */ firstBlockSize = allocSize - MAXALIGN(sizeof(GenerationContext)); - GenerationBlockInit(block, firstBlockSize); + GenerationBlockInit(set, block, firstBlockSize); /* add it to the doubly-linked list of blocks */ dlist_push_head(&set->blocks, &block->node); @@ -300,9 +238,14 @@ GenerationContextCreate(MemoryContext parent, /* * Compute the allocation chunk size limit for this context. * - * Follows similar ideas as AllocSet, see aset.c for details ... + * Limit the maximum size a non-dedicated chunk can be so that we can fit + * at least Generation_CHUNK_FRACTION of chunks this big onto the maximum + * sized block. We must further limit this value so that it's no more + * than MEMORYCHUNK_MAX_VALUE. We're unable to have non-dedicated chunks + * larger than that value as we store the chunk size in the MemoryChunk + * 'value' field in the call to MemoryChunkSetHdrMask(). */ - set->allocChunkLimit = maxBlockSize; + set->allocChunkLimit = Min(maxBlockSize, MEMORYCHUNK_MAX_VALUE); while ((Size) (set->allocChunkLimit + Generation_CHUNKHDRSZ) > (Size) ((Size) (maxBlockSize - Generation_BLOCKHDRSZ) / Generation_CHUNK_FRACTION)) set->allocChunkLimit >>= 1; @@ -310,7 +253,7 @@ GenerationContextCreate(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) set, T_GenerationContext, - &GenerationMethods, + MCTX_GENERATION_ID, parent, name); @@ -326,7 +269,7 @@ GenerationContextCreate(MemoryContext parent, * The code simply frees all the blocks in the context - we don't keep any * keeper blocks or anything like that. */ -static void +void GenerationReset(MemoryContext context) { GenerationContext *set = (GenerationContext *) context; @@ -371,7 +314,7 @@ GenerationReset(MemoryContext context) * GenerationDelete * Free all memory which is allocated in the given context. */ -static void +void GenerationDelete(MemoryContext context) { /* Reset to release all releasable GenerationBlocks */ @@ -393,12 +336,12 @@ GenerationDelete(MemoryContext context) * is marked, as mcxt.c will set it to UNDEFINED. In some paths we will * return space that is marked NOACCESS - GenerationRealloc has to beware! */ -static void * +void * GenerationAlloc(MemoryContext context, Size size) { GenerationContext *set = (GenerationContext *) context; GenerationBlock *block; - GenerationChunk *chunk; + MemoryChunk *chunk; Size chunk_size = MAXALIGN(size); Size required_size = chunk_size + Generation_CHUNKHDRSZ; @@ -414,6 +357,7 @@ GenerationAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; /* block with a single (used) chunk */ + block->context = set; block->blksize = blksize; block->nchunks = 1; block->nfree = 0; @@ -421,33 +365,33 @@ GenerationAlloc(MemoryContext context, Size size) /* the block is completely full */ block->freeptr = block->endptr = ((char *) block) + blksize; - chunk = (GenerationChunk *) (((char *) block) + Generation_BLOCKHDRSZ); - chunk->block = block; - chunk->context = set; - chunk->size = chunk_size; + chunk = (MemoryChunk *) (((char *) block) + Generation_BLOCKHDRSZ); + + /* mark the MemoryChunk as externally managed */ + MemoryChunkSetHdrMaskExternal(chunk, MCTX_GENERATION_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk_size) - set_sentinel(GenerationChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) GenerationChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* add the block to the list of allocated blocks */ dlist_push_head(&set->blocks, &block->node); /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) GenerationChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return GenerationChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -516,7 +460,7 @@ GenerationAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; /* initialize the new block */ - GenerationBlockInit(block, blksize); + GenerationBlockInit(set, block, blksize); /* add it to the doubly-linked list of blocks */ dlist_push_head(&set->blocks, &block->node); @@ -533,7 +477,7 @@ GenerationAlloc(MemoryContext context, Size size) Assert(block != NULL); Assert((block->endptr - block->freeptr) >= Generation_CHUNKHDRSZ + chunk_size); - chunk = (GenerationChunk *) block->freeptr; + chunk = (MemoryChunk *) block->freeptr; /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, Generation_CHUNKHDRSZ); @@ -543,29 +487,26 @@ GenerationAlloc(MemoryContext context, Size size) Assert(block->freeptr <= block->endptr); - chunk->block = block; - chunk->context = set; - chunk->size = chunk_size; - + MemoryChunkSetHdrMask(chunk, block, chunk_size, MCTX_GENERATION_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(GenerationChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) GenerationChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) GenerationChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return GenerationChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -574,8 +515,10 @@ GenerationAlloc(MemoryContext context, Size size) * mem_allocated field. */ static inline void -GenerationBlockInit(GenerationBlock *block, Size blksize) +GenerationBlockInit(GenerationContext *context, GenerationBlock *block, + Size blksize) { + block->context = context; block->blksize = blksize; block->nchunks = 0; block->nfree = 0; @@ -661,36 +604,49 @@ GenerationBlockFree(GenerationContext *set, GenerationBlock *block) * Update number of chunks in the block, and if all chunks in the block * are now free then discard the block. */ -static void -GenerationFree(MemoryContext context, void *pointer) +void +GenerationFree(void *pointer) { - GenerationContext *set = (GenerationContext *) context; - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); GenerationBlock *block; + GenerationContext *set; +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + Size chunksize; +#endif + + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + chunksize = block->endptr - (char *) pointer; +#endif + } + else + { + block = MemoryChunkGetBlock(chunk); +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + chunksize = MemoryChunkGetValue(chunk); +#endif + } /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - block = chunk->block; - #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunk->size) + if (chunk->requested_size < chunksize) if (!sentinel_ok(pointer, chunk->requested_size)) elog(WARNING, "detected write past chunk end in %s %p", - ((MemoryContext) set)->name, chunk); + ((MemoryContext) block->context)->name, chunk); #endif #ifdef CLOBBER_FREED_MEMORY - wipe_mem(pointer, chunk->size); + wipe_mem(pointer, chunksize); #endif - /* Reset context to NULL in freed chunks */ - chunk->context = NULL; - #ifdef MEMORY_CONTEXT_CHECKING - /* Reset requested_size to 0 in freed chunks */ - chunk->requested_size = 0; + /* Reset requested_size to InvalidAllocSize in freed chunks */ + chunk->requested_size = InvalidAllocSize; #endif block->nfree += 1; @@ -702,6 +658,8 @@ GenerationFree(MemoryContext context, void *pointer) if (block->nfree < block->nchunks) return; + set = block->context; + /* Don't try to free the keeper block, just mark it empty */ if (block == set->keeper) { @@ -732,7 +690,7 @@ GenerationFree(MemoryContext context, void *pointer) */ dlist_delete(&block->node); - context->mem_allocated -= block->blksize; + set->header.mem_allocated -= block->blksize; free(block); } @@ -742,18 +700,30 @@ GenerationFree(MemoryContext context, void *pointer) * and discard the old one. The only exception is when the new size fits * into the old chunk - in that case we just update chunk header. */ -static void * -GenerationRealloc(MemoryContext context, void *pointer, Size size) +void * +GenerationRealloc(void *pointer, Size size) { - GenerationContext *set = (GenerationContext *) context; - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationContext *set; + GenerationBlock *block; GenerationPointer newPointer; Size oldsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - oldsize = chunk->size; + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); + oldsize = block->endptr - (char *) pointer; + } + else + { + block = MemoryChunkGetBlock(chunk); + oldsize = MemoryChunkGetValue(chunk); + } + + set = block->context; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ @@ -848,7 +818,7 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) memcpy(newPointer, pointer, oldsize); /* free old chunk */ - GenerationFree((MemoryContext) set, pointer); + GenerationFree(pointer); return newPointer; } @@ -858,23 +828,48 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -GenerationGetChunkSpace(MemoryContext context, void *pointer) +MemoryContext +GenerationGetChunkContext(void *pointer) { - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); - Size result; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationBlock *block; - VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - result = chunk->size + Generation_CHUNKHDRSZ; - VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return result; + if (MemoryChunkIsExternal(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (GenerationBlock *) MemoryChunkGetBlock(chunk); + + return &block->context->header; +} + +/* + * GenerationGetChunkSpace + * Given a currently-allocated chunk, determine the total space + * it occupies (including all memory-allocation overhead). + */ +Size +GenerationGetChunkSpace(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + Size chunksize; + + if (MemoryChunkIsExternal(chunk)) + { + GenerationBlock *block = ExternalChunkGetBlock(chunk); + + chunksize = block->endptr - (char *) pointer; + } + else + chunksize = MemoryChunkGetValue(chunk); + + return Generation_CHUNKHDRSZ + chunksize; } /* * GenerationIsEmpty * Is a GenerationContext empty of any allocated space? */ -static bool +bool GenerationIsEmpty(MemoryContext context) { GenerationContext *set = (GenerationContext *) context; @@ -903,7 +898,7 @@ GenerationIsEmpty(MemoryContext context) * XXX freespace only accounts for empty space at the end of the block, not * space of freed chunks (which is unknown). */ -static void +void GenerationStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr) @@ -961,7 +956,7 @@ GenerationStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void GenerationCheck(MemoryContext context) { GenerationContext *gen = (GenerationContext *) context; @@ -976,6 +971,7 @@ GenerationCheck(MemoryContext context) int nfree, nchunks; char *ptr; + bool has_external_chunk = false; total_allocated += block->blksize; @@ -987,6 +983,11 @@ GenerationCheck(MemoryContext context) elog(WARNING, "problem in Generation %s: number of free chunks %d in block %p exceeds %d allocated", name, block->nfree, block, block->nchunks); + /* check block belongs to the correct context */ + if (block->context != gen) + elog(WARNING, "problem in Generation %s: bogus context link in block %p", + name, block); + /* Now walk through the chunks and count them. */ nfree = 0; nchunks = 0; @@ -994,42 +995,47 @@ GenerationCheck(MemoryContext context) while (ptr < block->freeptr) { - GenerationChunk *chunk = (GenerationChunk *) ptr; + MemoryChunk *chunk = (MemoryChunk *) ptr; + GenerationBlock *chunkblock; + Size chunksize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); + if (MemoryChunkIsExternal(chunk)) + { + chunkblock = ExternalChunkGetBlock(chunk); + chunksize = block->endptr - (char *) MemoryChunkGetPointer(chunk); + has_external_chunk = true; + } + else + { + chunkblock = MemoryChunkGetBlock(chunk); + chunksize = MemoryChunkGetValue(chunk); + } + /* move to the next chunk */ - ptr += (chunk->size + Generation_CHUNKHDRSZ); + ptr += (chunksize + Generation_CHUNKHDRSZ); nchunks += 1; /* chunks have both block and context pointers, so check both */ - if (chunk->block != block) + if (chunkblock != block) elog(WARNING, "problem in Generation %s: bogus block link in block %p, chunk %p", name, block, chunk); - /* - * Check for valid context pointer. Note this is an incomplete - * test, since palloc(0) produces an allocated chunk with - * requested_size == 0. - */ - if ((chunk->requested_size > 0 && chunk->context != gen) || - (chunk->context != gen && chunk->context != NULL)) - elog(WARNING, "problem in Generation %s: bogus context link in block %p, chunk %p", - name, block, chunk); - - /* now make sure the chunk size is correct */ - if (chunk->size < chunk->requested_size || - chunk->size != MAXALIGN(chunk->size)) - elog(WARNING, "problem in Generation %s: bogus chunk size in block %p, chunk %p", - name, block, chunk); /* is chunk allocated? */ - if (chunk->context != NULL) + if (chunk->requested_size != InvalidAllocSize) { - /* check sentinel, but only in allocated blocks */ - if (chunk->requested_size < chunk->size && + /* now make sure the chunk size is correct */ + if (chunksize < chunk->requested_size || + chunksize != MAXALIGN(chunksize)) + elog(WARNING, "problem in Generation %s: bogus chunk size in block %p, chunk %p", + name, block, chunk); + + /* check sentinel */ + if (chunk->requested_size < chunksize && !sentinel_ok(chunk, Generation_CHUNKHDRSZ + chunk->requested_size)) elog(WARNING, "problem in Generation %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); @@ -1041,7 +1047,7 @@ GenerationCheck(MemoryContext context) * If chunk is allocated, disallow external access to private part * of chunk header. */ - if (chunk->context != NULL) + if (chunk->requested_size != InvalidAllocSize) VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); } @@ -1056,6 +1062,11 @@ GenerationCheck(MemoryContext context) if (nfree != block->nfree) elog(WARNING, "problem in Generation %s: number of free chunks %d in block %p does not match header %d", name, nfree, block, block->nfree); + + if (has_external_chunk && nchunks > 1) + elog(WARNING, "problem in Generation %s: external chunk on non-dedicated block %p", + name, block); + } Assert(total_allocated == context->mem_allocated); diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index e12be1b9bd..7c53222b9d 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -29,12 +29,57 @@ #include "utils/fmgrprotos.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_internal.h" /***************************************************************************** * GLOBAL MEMORY * *****************************************************************************/ +static const MemoryContextMethods mcxt_methods[] = { + /* aset.c */ + [MCTX_ASET_ID].alloc = AllocSetAlloc, + [MCTX_ASET_ID].free_p = AllocSetFree, + [MCTX_ASET_ID].realloc = AllocSetRealloc, + [MCTX_ASET_ID].reset = AllocSetReset, + [MCTX_ASET_ID].delete_context = AllocSetDelete, + [MCTX_ASET_ID].get_chunk_context = AllocSetGetChunkContext, + [MCTX_ASET_ID].get_chunk_space = AllocSetGetChunkSpace, + [MCTX_ASET_ID].is_empty = AllocSetIsEmpty, + [MCTX_ASET_ID].stats = AllocSetStats, +#ifdef MEMORY_CONTEXT_CHECKING + [MCTX_ASET_ID].check = AllocSetCheck, +#endif + + /* generation.c */ + [MCTX_GENERATION_ID].alloc = GenerationAlloc, + [MCTX_GENERATION_ID].free_p = GenerationFree, + [MCTX_GENERATION_ID].realloc = GenerationRealloc, + [MCTX_GENERATION_ID].reset = GenerationReset, + [MCTX_GENERATION_ID].delete_context = GenerationDelete, + [MCTX_GENERATION_ID].get_chunk_context = GenerationGetChunkContext, + [MCTX_GENERATION_ID].get_chunk_space = GenerationGetChunkSpace, + [MCTX_GENERATION_ID].is_empty = GenerationIsEmpty, + [MCTX_GENERATION_ID].stats = GenerationStats, +#ifdef MEMORY_CONTEXT_CHECKING + [MCTX_GENERATION_ID].check = GenerationCheck, +#endif + + /* slab.c */ + [MCTX_SLAB_ID].alloc = SlabAlloc, + [MCTX_SLAB_ID].free_p = SlabFree, + [MCTX_SLAB_ID].realloc = SlabRealloc, + [MCTX_SLAB_ID].reset = SlabReset, + [MCTX_SLAB_ID].delete_context = SlabDelete, + [MCTX_SLAB_ID].get_chunk_context = SlabGetChunkContext, + [MCTX_SLAB_ID].get_chunk_space = SlabGetChunkSpace, + [MCTX_SLAB_ID].is_empty = SlabIsEmpty, + [MCTX_SLAB_ID].stats = SlabStats +#ifdef MEMORY_CONTEXT_CHECKING + ,[MCTX_SLAB_ID].check = SlabCheck +#endif +}; + /* * CurrentMemoryContext * Default memory context for allocations. @@ -73,6 +118,13 @@ static void MemoryContextStatsPrint(MemoryContext context, void *passthru, #define AssertNotInCriticalSection(context) \ Assert(CritSectionCount == 0 || (context)->allowInCritSection) +/* + * Call the given function in the MemoryContextMethods for the memory context + * type that 'pointer' belongs to. + */ +#define MCXT_METHOD(pointer, method) \ + mcxt_methods[GetMemoryChunkMethodID(pointer)].method + /***************************************************************************** * EXPORTED ROUTINES * @@ -422,6 +474,17 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) context->allowInCritSection = allow; } +/* + * GetMemoryChunkContext + * Given a currently-allocated chunk, determine the MemoryContext that + * the chunk belongs to. + */ +MemoryContext +GetMemoryChunkContext(void *pointer) +{ + return MCXT_METHOD(pointer, get_chunk_context) (pointer); +} + /* * GetMemoryChunkSpace * Given a currently-allocated chunk, determine the total space @@ -433,9 +496,7 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) Size GetMemoryChunkSpace(void *pointer) { - MemoryContext context = GetMemoryChunkContext(pointer); - - return context->methods->get_chunk_space(context, pointer); + return MCXT_METHOD(pointer, get_chunk_space) (pointer); } /* @@ -814,7 +875,7 @@ MemoryContextContains(MemoryContext context, void *pointer) void MemoryContextCreate(MemoryContext node, NodeTag tag, - const MemoryContextMethods *methods, + MemoryContextMethodID method_id, MemoryContext parent, const char *name) { @@ -824,7 +885,7 @@ MemoryContextCreate(MemoryContext node, /* Initialize all standard fields of memory context header */ node->type = tag; node->isReset = true; - node->methods = methods; + node->methods = &mcxt_methods[method_id]; node->parent = parent; node->firstchild = NULL; node->mem_allocated = 0; @@ -1174,9 +1235,11 @@ palloc_extended(Size size, int flags) void pfree(void *pointer) { +#ifdef USE_VALGRIND MemoryContext context = GetMemoryChunkContext(pointer); +#endif - context->methods->free_p(context, pointer); + MCXT_METHOD(pointer, free_p) (pointer); VALGRIND_MEMPOOL_FREE(context, pointer); } @@ -1187,7 +1250,9 @@ pfree(void *pointer) void * repalloc(void *pointer, Size size) { +#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND) MemoryContext context = GetMemoryChunkContext(pointer); +#endif void *ret; if (!AllocSizeIsValid(size)) @@ -1198,15 +1263,17 @@ repalloc(void *pointer, Size size) /* isReset must be false already */ Assert(!context->isReset); - ret = context->methods->realloc(context, pointer, size); + ret = MCXT_METHOD(pointer, realloc) (pointer, size); if (unlikely(ret == NULL)) { + MemoryContext cxt = GetMemoryChunkContext(pointer); + MemoryContextStats(TopMemoryContext); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"), errdetail("Failed on request of size %zu in memory context \"%s\".", - size, context->name))); + size, cxt->name))); } VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size); @@ -1257,7 +1324,9 @@ MemoryContextAllocHuge(MemoryContext context, Size size) void * repalloc_huge(void *pointer, Size size) { +#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND) MemoryContext context = GetMemoryChunkContext(pointer); +#endif void *ret; if (!AllocHugeSizeIsValid(size)) @@ -1268,15 +1337,17 @@ repalloc_huge(void *pointer, Size size) /* isReset must be false already */ Assert(!context->isReset); - ret = context->methods->realloc(context, pointer, size); + ret = MCXT_METHOD(pointer, realloc) (pointer, size); if (unlikely(ret == NULL)) { + MemoryContext cxt = GetMemoryChunkContext(pointer); + MemoryContextStats(TopMemoryContext); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"), errdetail("Failed on request of size %zu in memory context \"%s\".", - size, context->name))); + size, cxt->name))); } VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size); diff --git a/src/backend/utils/mmgr/slab.c b/src/backend/utils/mmgr/slab.c index 67d97b22e5..e042e596f7 100644 --- a/src/backend/utils/mmgr/slab.c +++ b/src/backend/utils/mmgr/slab.c @@ -55,6 +55,8 @@ #include "lib/ilist.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" /* * SlabContext is a specialized implementation of MemoryContext. @@ -90,75 +92,23 @@ typedef struct SlabBlock dlist_node node; /* doubly-linked list */ int nfree; /* number of free chunks */ int firstFreeChunk; /* index of the first free chunk in the block */ -} SlabBlock; - -/* - * SlabChunk - * The prefix of each piece of memory in a SlabBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "slab" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). Since we support no machines on - * which MAXALIGN is more than twice sizeof(void *), this happens without any - * special hacking in this struct declaration. But there is a static - * assertion below that the alignment is done correctly. - */ -typedef struct SlabChunk -{ - SlabBlock *block; /* block owning this chunk */ SlabContext *slab; /* owning context */ - /* there must not be any padding to reach a MAXALIGN boundary here! */ -} SlabChunk; +} SlabBlock; +#define Slab_CHUNKHDRSZ sizeof(MemoryChunk) #define SlabPointerGetChunk(ptr) \ - ((SlabChunk *)(((char *)(ptr)) - sizeof(SlabChunk))) + ((MemoryChunk *)(((char *)(ptr)) - sizeof(MemoryChunk))) #define SlabChunkGetPointer(chk) \ - ((void *)(((char *)(chk)) + sizeof(SlabChunk))) + ((void *)(((char *)(chk)) + sizeof(MemoryChunk))) #define SlabBlockGetChunk(slab, block, idx) \ - ((SlabChunk *) ((char *) (block) + sizeof(SlabBlock) \ + ((MemoryChunk *) ((char *) (block) + sizeof(SlabBlock) \ + (idx * slab->fullChunkSize))) #define SlabBlockStart(block) \ ((char *) block + sizeof(SlabBlock)) #define SlabChunkIndex(slab, block, chunk) \ (((char *) chunk - SlabBlockStart(block)) / slab->fullChunkSize) -/* - * These functions implement the MemoryContext API for Slab contexts. - */ -static void *SlabAlloc(MemoryContext context, Size size); -static void SlabFree(MemoryContext context, void *pointer); -static void *SlabRealloc(MemoryContext context, void *pointer, Size size); -static void SlabReset(MemoryContext context); -static void SlabDelete(MemoryContext context); -static Size SlabGetChunkSpace(MemoryContext context, void *pointer); -static bool SlabIsEmpty(MemoryContext context); -static void SlabStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); -#ifdef MEMORY_CONTEXT_CHECKING -static void SlabCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for Slab contexts. - */ -static const MemoryContextMethods SlabMethods = { - SlabAlloc, - SlabFree, - SlabRealloc, - SlabReset, - SlabDelete, - SlabGetChunkSpace, - SlabIsEmpty, - SlabStats -#ifdef MEMORY_CONTEXT_CHECKING - ,SlabCheck -#endif -}; - - /* * SlabContextCreate * Create a new Slab context. @@ -168,8 +118,7 @@ static const MemoryContextMethods SlabMethods = { * blockSize: allocation block size * chunkSize: allocation chunk size * - * The chunkSize may not exceed: - * MAXALIGN_DOWN(SIZE_MAX) - MAXALIGN(sizeof(SlabBlock)) - sizeof(SlabChunk) + * The MAXALIGN(chunkSize) may not exceed MEMORYCHUNK_MAX_VALUE */ MemoryContext SlabContextCreate(MemoryContext parent, @@ -184,19 +133,14 @@ SlabContextCreate(MemoryContext parent, SlabContext *slab; int i; - /* Assert we padded SlabChunk properly */ - StaticAssertStmt(sizeof(SlabChunk) == MAXALIGN(sizeof(SlabChunk)), - "sizeof(SlabChunk) is not maxaligned"); - StaticAssertStmt(offsetof(SlabChunk, slab) + sizeof(MemoryContext) == - sizeof(SlabChunk), - "padding calculation in SlabChunk is wrong"); + Assert(MAXALIGN(chunkSize) <= MEMORYCHUNK_MAX_VALUE); /* Make sure the linked list node fits inside a freed chunk */ if (chunkSize < sizeof(int)) chunkSize = sizeof(int); /* chunk, including SLAB header (both addresses nicely aligned) */ - fullChunkSize = sizeof(SlabChunk) + MAXALIGN(chunkSize); + fullChunkSize = Slab_CHUNKHDRSZ + MAXALIGN(chunkSize); /* Make sure the block can store at least one chunk. */ if (blockSize < fullChunkSize + sizeof(SlabBlock)) @@ -265,7 +209,7 @@ SlabContextCreate(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) slab, T_SlabContext, - &SlabMethods, + MCTX_SLAB_ID, parent, name); @@ -279,7 +223,7 @@ SlabContextCreate(MemoryContext parent, * The code simply frees all the blocks in the context - we don't keep any * keeper blocks or anything like that. */ -static void +void SlabReset(MemoryContext context) { int i; @@ -322,7 +266,7 @@ SlabReset(MemoryContext context) * SlabDelete * Free all memory which is allocated in the given context. */ -static void +void SlabDelete(MemoryContext context) { /* Reset to release all the SlabBlocks */ @@ -336,12 +280,12 @@ SlabDelete(MemoryContext context) * Returns pointer to allocated memory of given size or NULL if * request could not be completed; memory is added to the slab. */ -static void * +void * SlabAlloc(MemoryContext context, Size size) { SlabContext *slab = castNode(SlabContext, context); SlabBlock *block; - SlabChunk *chunk; + MemoryChunk *chunk; int idx; Assert(slab); @@ -370,6 +314,7 @@ SlabAlloc(MemoryContext context, Size size) block->nfree = slab->chunksPerBlock; block->firstFreeChunk = 0; + block->slab = slab; /* * Put all the chunks on a freelist. Walk the chunks and point each @@ -378,7 +323,7 @@ SlabAlloc(MemoryContext context, Size size) for (idx = 0; idx < slab->chunksPerBlock; idx++) { chunk = SlabBlockGetChunk(slab, block, idx); - *(int32 *) SlabChunkGetPointer(chunk) = (idx + 1); + *(int32 *) MemoryChunkGetPointer(chunk) = (idx + 1); } /* @@ -426,8 +371,8 @@ SlabAlloc(MemoryContext context, Size size) * Remove the chunk from the freelist head. The index of the next free * chunk is stored in the chunk itself. */ - VALGRIND_MAKE_MEM_DEFINED(SlabChunkGetPointer(chunk), sizeof(int32)); - block->firstFreeChunk = *(int32 *) SlabChunkGetPointer(chunk); + VALGRIND_MAKE_MEM_DEFINED(MemoryChunkGetPointer(chunk), sizeof(int32)); + block->firstFreeChunk = *(int32 *) MemoryChunkGetPointer(chunk); Assert(block->firstFreeChunk >= 0); Assert(block->firstFreeChunk <= slab->chunksPerBlock); @@ -464,47 +409,47 @@ SlabAlloc(MemoryContext context, Size size) slab->minFreeChunks = 0; /* Prepare to initialize the chunk header. */ - VALGRIND_MAKE_MEM_UNDEFINED(chunk, sizeof(SlabChunk)); - - chunk->block = block; - chunk->slab = slab; + VALGRIND_MAKE_MEM_UNDEFINED(chunk, Slab_CHUNKHDRSZ); + MemoryChunkSetHdrMask(chunk, block, MAXALIGN(slab->chunkSize), + MCTX_SLAB_ID); #ifdef MEMORY_CONTEXT_CHECKING /* slab mark to catch clobber of "unused" space */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) { - set_sentinel(SlabChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); VALGRIND_MAKE_MEM_NOACCESS(((char *) chunk) + - sizeof(SlabChunk) + slab->chunkSize, + Slab_CHUNKHDRSZ + slab->chunkSize, slab->fullChunkSize - - (slab->chunkSize + sizeof(SlabChunk))); + (slab->chunkSize + Slab_CHUNKHDRSZ)); } #endif + #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) SlabChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif Assert(slab->nblocks * slab->blockSize == context->mem_allocated); - return SlabChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * SlabFree * Frees allocated memory; memory is removed from the slab. */ -static void -SlabFree(MemoryContext context, void *pointer) +void +SlabFree(void *pointer) { int idx; - SlabContext *slab = castNode(SlabContext, context); - SlabChunk *chunk = SlabPointerGetChunk(pointer); - SlabBlock *block = chunk->block; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) if (!sentinel_ok(pointer, slab->chunkSize)) elog(WARNING, "detected write past chunk end in %s %p", slab->header.name, chunk); @@ -560,13 +505,13 @@ SlabFree(MemoryContext context, void *pointer) { free(block); slab->nblocks--; - context->mem_allocated -= slab->blockSize; + slab->header.mem_allocated -= slab->blockSize; } else dlist_push_head(&slab->freelist[block->nfree], &block->node); Assert(slab->nblocks >= 0); - Assert(slab->nblocks * slab->blockSize == context->mem_allocated); + Assert(slab->nblocks * slab->blockSize == slab->header.mem_allocated); } /* @@ -582,13 +527,14 @@ SlabFree(MemoryContext context, void *pointer) * rather pointless - Slab is meant for chunks of constant size, and moreover * realloc is usually used to enlarge the chunk. */ -static void * -SlabRealloc(MemoryContext context, void *pointer, Size size) +void * +SlabRealloc(void *pointer, Size size) { - SlabContext *slab = castNode(SlabContext, context); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; Assert(slab); - /* can't do actual realloc with slab, but let's try to be gentle */ if (size == slab->chunkSize) return pointer; @@ -597,15 +543,33 @@ SlabRealloc(MemoryContext context, void *pointer, Size size) return NULL; /* keep compiler quiet */ } +/* + * SlabGetChunkContext + * Return the MemoryContext that 'pointer' belongs to. + */ +MemoryContext +SlabGetChunkContext(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; + + Assert(slab != NULL); + + return &slab->header; +} + /* * SlabGetChunkSpace * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -SlabGetChunkSpace(MemoryContext context, void *pointer) +Size +SlabGetChunkSpace(void *pointer) { - SlabContext *slab = castNode(SlabContext, context); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; Assert(slab); @@ -616,7 +580,7 @@ SlabGetChunkSpace(MemoryContext context, void *pointer) * SlabIsEmpty * Is an Slab empty of any allocated space? */ -static bool +bool SlabIsEmpty(MemoryContext context) { SlabContext *slab = castNode(SlabContext, context); @@ -635,7 +599,7 @@ SlabIsEmpty(MemoryContext context) * totals: if not NULL, add stats about this context into *totals. * print_to_stderr: print stats to stderr if true, elog otherwise. */ -static void +void SlabStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, @@ -697,7 +661,7 @@ SlabStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void SlabCheck(MemoryContext context) { int i; @@ -728,6 +692,11 @@ SlabCheck(MemoryContext context) elog(WARNING, "problem in slab %s: number of free chunks %d in block %p does not match freelist %d", name, block->nfree, block, i); + /* make sure the slab pointer correctly points to this context */ + if (block->slab != slab) + elog(WARNING, "problem in slab %s: bogus slab link in block %p", + name, block); + /* reset the bitmap of free chunks for this block */ memset(slab->freechunks, 0, (slab->chunksPerBlock * sizeof(bool))); idx = block->firstFreeChunk; @@ -742,7 +711,7 @@ SlabCheck(MemoryContext context) nfree = 0; while (idx < slab->chunksPerBlock) { - SlabChunk *chunk; + MemoryChunk *chunk; /* count the chunk as free, add it to the bitmap */ nfree++; @@ -750,8 +719,8 @@ SlabCheck(MemoryContext context) /* read index of the next free chunk */ chunk = SlabBlockGetChunk(slab, block, idx); - VALGRIND_MAKE_MEM_DEFINED(SlabChunkGetPointer(chunk), sizeof(int32)); - idx = *(int32 *) SlabChunkGetPointer(chunk); + VALGRIND_MAKE_MEM_DEFINED(MemoryChunkGetPointer(chunk), sizeof(int32)); + idx = *(int32 *) MemoryChunkGetPointer(chunk); } for (j = 0; j < slab->chunksPerBlock; j++) @@ -759,19 +728,19 @@ SlabCheck(MemoryContext context) /* non-zero bit in the bitmap means chunk the chunk is used */ if (!slab->freechunks[j]) { - SlabChunk *chunk = SlabBlockGetChunk(slab, block, j); - - /* chunks have both block and slab pointers, so check both */ - if (chunk->block != block) + MemoryChunk *chunk = SlabBlockGetChunk(slab, block, j); + SlabBlock *chunkblock = (SlabBlock *) MemoryChunkGetBlock(chunk); + + /* + * check the chunk's blockoffset correctly points back to + * the block + */ + if (chunkblock != block) elog(WARNING, "problem in slab %s: bogus block link in block %p, chunk %p", name, block, chunk); - if (chunk->slab != slab) - elog(WARNING, "problem in slab %s: bogus slab link in block %p, chunk %p", - name, block, chunk); - /* there might be sentinel (thanks to alignment) */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) if (!sentinel_ok(chunk, slab->chunkSize)) elog(WARNING, "problem in slab %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); diff --git a/src/include/nodes/memnodes.h b/src/include/nodes/memnodes.h index 16cd56da6d..63d07358cd 100644 --- a/src/include/nodes/memnodes.h +++ b/src/include/nodes/memnodes.h @@ -59,11 +59,12 @@ typedef struct MemoryContextMethods { void *(*alloc) (MemoryContext context, Size size); /* call this free_p in case someone #define's free() */ - void (*free_p) (MemoryContext context, void *pointer); - void *(*realloc) (MemoryContext context, void *pointer, Size size); + void (*free_p) (void *pointer); + void *(*realloc) (void *pointer, Size size); void (*reset) (MemoryContext context); void (*delete_context) (MemoryContext context); - Size (*get_chunk_space) (MemoryContext context, void *pointer); + MemoryContext (*get_chunk_context) (void *pointer); + Size (*get_chunk_space) (void *pointer); bool (*is_empty) (MemoryContext context); void (*stats) (MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, diff --git a/src/include/utils/memutils.h b/src/include/utils/memutils.h index 495d1af201..52bc41ec53 100644 --- a/src/include/utils/memutils.h +++ b/src/include/utils/memutils.h @@ -41,8 +41,11 @@ #define AllocSizeIsValid(size) ((Size) (size) <= MaxAllocSize) +/* Must be less than SIZE_MAX */ #define MaxAllocHugeSize (SIZE_MAX / 2) +#define InvalidAllocSize SIZE_MAX + #define AllocHugeSizeIsValid(size) ((Size) (size) <= MaxAllocHugeSize) @@ -79,6 +82,7 @@ extern void MemoryContextDeleteChildren(MemoryContext context); extern void MemoryContextSetIdentifier(MemoryContext context, const char *id); extern void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent); +extern MemoryContext GetMemoryChunkContext(void *pointer); extern Size GetMemoryChunkSpace(void *pointer); extern MemoryContext MemoryContextGetParent(MemoryContext context); extern bool MemoryContextIsEmpty(MemoryContext context); @@ -98,53 +102,6 @@ extern bool MemoryContextContains(MemoryContext context, void *pointer); #define MemoryContextCopyAndSetIdentifier(cxt, id) \ MemoryContextSetIdentifier(cxt, MemoryContextStrdup(cxt, id)) -/* - * GetMemoryChunkContext - * Given a currently-allocated chunk, determine the context - * it belongs to. - * - * All chunks allocated by any memory context manager are required to be - * preceded by the corresponding MemoryContext stored, without padding, in the - * preceding sizeof(void*) bytes. A currently-allocated chunk must contain a - * backpointer to its owning context. The backpointer is used by pfree() and - * repalloc() to find the context to call. - */ -#ifndef FRONTEND -static inline MemoryContext -GetMemoryChunkContext(void *pointer) -{ - MemoryContext context; - - /* - * Try to detect bogus pointers handed to us, poorly though we can. - * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an - * allocated chunk. - */ - Assert(pointer != NULL); - Assert(pointer == (void *) MAXALIGN(pointer)); - - /* - * OK, it's probably safe to look at the context. - */ - context = *(MemoryContext *) (((char *) pointer) - sizeof(void *)); - - AssertArg(MemoryContextIsValid(context)); - - return context; -} -#endif - -/* - * This routine handles the context-type-independent part of memory - * context creation. It's intended to be called from context-type- - * specific creation routines, and noplace else. - */ -extern void MemoryContextCreate(MemoryContext node, - NodeTag tag, - const MemoryContextMethods *methods, - MemoryContext parent, - const char *name); - extern void HandleLogMemoryContextInterrupt(void); extern void ProcessLogMemoryContextInterrupt(void); diff --git a/src/include/utils/memutils_internal.h b/src/include/utils/memutils_internal.h new file mode 100644 index 0000000000..d1d3becc19 --- /dev/null +++ b/src/include/utils/memutils_internal.h @@ -0,0 +1,130 @@ +/*------------------------------------------------------------------------- + * + * memutils_internal.h + * This file contains declarations for memory allocation utility + * functions for internal use. + * + * + * Portions Copyright (c) 2022, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/utils/memutils_internal.h + * + *------------------------------------------------------------------------- + */ + +#ifndef MEMUTILS_INTERNAL_H +#define MEMUTILS_INTERNAL_H + +#include "utils/memutils.h" + +extern void *AllocSetAlloc(MemoryContext context, Size size); +extern void AllocSetFree(void *pointer); +extern void *AllocSetRealloc(void *pointer, Size size); +extern void AllocSetReset(MemoryContext context); +extern void AllocSetDelete(MemoryContext context); +extern MemoryContext AllocSetGetChunkContext(void *pointer); +extern Size AllocSetGetChunkSpace(void *pointer); +extern bool AllocSetIsEmpty(MemoryContext context); +extern void AllocSetStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); + +#ifdef MEMORY_CONTEXT_CHECKING +extern void AllocSetCheck(MemoryContext context); +#endif + + +extern void *GenerationAlloc(MemoryContext context, Size size); +extern void GenerationFree(void *pointer); +extern void *GenerationRealloc(void *pointer, Size size); +extern void GenerationReset(MemoryContext context); +extern void GenerationDelete(MemoryContext context); +extern MemoryContext GenerationGetChunkContext(void *pointer); +extern Size GenerationGetChunkSpace(void *pointer); +extern bool GenerationIsEmpty(MemoryContext context); +extern void GenerationStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); + +#ifdef MEMORY_CONTEXT_CHECKING +extern void GenerationCheck(MemoryContext context); +#endif + + +/* + * These functions implement the MemoryContext API for Slab contexts. + */ +extern void *SlabAlloc(MemoryContext context, Size size); +extern void SlabFree(void *pointer); +extern void *SlabRealloc(void *pointer, Size size); +extern void SlabReset(MemoryContext context); +extern void SlabDelete(MemoryContext context); +extern MemoryContext SlabGetChunkContext(void *pointer); +extern Size SlabGetChunkSpace(void *pointer); +extern bool SlabIsEmpty(MemoryContext context); +extern void SlabStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); +#ifdef MEMORY_CONTEXT_CHECKING +extern void SlabCheck(MemoryContext context); +#endif + +/* + * MemoryContextMethodID + * A unique identifier for each MemoryContext implementation which + * indicates the index into the mcxt_methods[] array. See mcxt.c. + */ +typedef enum MemoryContextMethodID +{ + MCTX_ASET_ID, + MCTX_GENERATION_ID, + MCTX_SLAB_ID, +} MemoryContextMethodID; + +/* + * The number of bits that 8-byte memory chunk headers can use to encode the + * MemoryContextMethodID. + */ +#define MEMORY_CONTEXT_METHODID_BITS 3 +/* + * The maximum possible value of for a MemoryContextMethodID and the bitmask + * for binary ANDing out unrelated bits in the 8-byte chunk header. This must + * be set to the maximum value that can be represented by + * MEMORY_CONTEXT_METHODID_BITS bits. + */ +#define MEMORY_CONTEXT_METHODID_MASK UINT64CONST(7) + +/* + * This routine handles the context-type-independent part of memory + * context creation. It's intended to be called from context-type- + * specific creation routines, and noplace else. + */ +extern void MemoryContextCreate(MemoryContext node, + NodeTag tag, + MemoryContextMethodID method_id, + MemoryContext parent, + const char *name); + +static inline MemoryContextMethodID +GetMemoryChunkMethodID(void *pointer) +{ + uint64 header; + + /* + * Try to detect bogus pointers handed to us, poorly though we can. + * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an + * allocated chunk. + */ + Assert(pointer != NULL); + Assert(pointer == (void *) MAXALIGN(pointer)); + + header = *((uint64 *) ((char *) pointer - sizeof(uint64))); + + return header & MEMORY_CONTEXT_METHODID_MASK; +} + +#endif /* MEMUTILS_INTERNAL_H */ diff --git a/src/include/utils/memutils_memorychunk.h b/src/include/utils/memutils_memorychunk.h new file mode 100644 index 0000000000..8697449a93 --- /dev/null +++ b/src/include/utils/memutils_memorychunk.h @@ -0,0 +1,231 @@ +/*------------------------------------------------------------------------- + * + * memutils_memorychunk.h + * Here we define a struct named MemoryChunk which implementations of + * MemoryContexts may use as a header for chunks of memory they allocate. + * + * A MemoryChunk provides a lightweight header which a MemoryContext can use + * to store a reference back to the block the which the given chunk is + * allocated on and also an additional 30-bits to store another value such as + * the size of the allocated chunk. + * + * Although MemoryChunks are used by each of our MemoryContexts, future + * implementations may choose to implement their own method for storing chunk + * headers. The only requirement is that the header end with an 8-byte value + * which the least significant 3-bits of are set to the MemoryContextMethodID + * of the given context. + * + * By default, a MemoryChunk is 8 bytes in size, however when + * MEMORY_CONTEXT_CHECKING is defined the header becomes 16 bytes in size due + * to the additional requested_size field. The MemoryContext may use this + * field for whatever they wish, but it is intended to be used for additional + * checks which are only done in MEMORY_CONTEXT_CHECKING builds. + * + * The MemoryChunk contains a uint64 field named 'hdrmask'. This field is + * used to encode 4 separate pieces of information. Starting with the least + * significant bits of 'hdrmask', the bit space is reserved as follows: + * + * 1. 3-bits to indicate the MemoryContextMethodID as defined by + * MEMORY_CONTEXT_METHODID_MASK + * 2. 1-bit to denote an "external" chunk (see below) + * 3. 30-bits reserved for the MemoryContext to use for anything it + * requires. Most MemoryContext likely want to store the size of the + * chunk here. + * 4. 30-bits for the number of bytes that must be subtracted from the chunk + * to obtain the address of the block that the chunk is stored on. + * + * In some cases, for example when memory allocations become large, it's + * possible fields 3 and 4 above are not large enough to store the values + * required for the chunk. In this case, the MemoryContext can choose to mark + * the chunk as "external" by calling the MemoryChunkSetExternal() function. + * When this is done, fields 3 and 4 are unavailable for use by the + * MemoryContext and it's up to the MemoryContext itself to devise its own + * method for getting the reference to the block. + * + * Interface: + * + * MemoryChunkSetHdrMask: + * Used to set up a non-external MemoryChunk. + * + * MemoryChunkSetHdrMaskExternal: + * Used to set up an externally managed MemoryChunk. + * + * MemoryChunkIsExternal: + * Determine if the given MemoryChunk is externally managed, i.e. + * MemoryChunkSetHdrMaskExternal() was called on the chunk. + * + * MemoryChunkGetValue: + * For non-external chunks, return the stored 30-bit value as it was set + * in the call to MemoryChunkSetHdrMask(). + * + * MemoryChunkGetBlock: + * For non-external chunks, return a pointer to the block as it was set + * in the call to MemoryChunkSetHdrMask(). + * + * Also exports: + * MEMORYCHUNK_MAX_VALUE + * MEMORYCHUNK_MAX_BLOCKOFFSET + * PointerGetMemoryChunk + * MemoryChunkGetPointer + * + * Portions Copyright (c) 2022, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/utils/memutils_memorychunk.h + * + *------------------------------------------------------------------------- + */ + +#ifndef MEMUTILS_MEMORYCHUNK_H +#define MEMUTILS_MEMORYCHUNK_H + +#include "utils/memutils_internal.h" + + /* + * The maximum allowed value that MemoryContexts can store in the value + * field. Must be 1 less than a power of 2. + */ +#define MEMORYCHUNK_MAX_VALUE UINT64CONST(0x3FFFFFFF) + +/* + * The maximum distance in bytes that a MemoryChunk can be offset from the + * block that is storing the chunk. Must be 1 less than a power of 2. + */ +#define MEMORYCHUNK_MAX_BLOCKOFFSET UINT64CONST(0x3FFFFFFF) + +/* define the least significant base-0 bit of each portion of the hdrmask */ +#define MEMORYCHUNK_EXTERNAL_BASEBIT MEMORY_CONTEXT_METHODID_BITS +#define MEMORYCHUNK_VALUE_BASEBIT (MEMORYCHUNK_EXTERNAL_BASEBIT + 1) +#define MEMORYCHUNK_BLOCKOFFSET_BASEBIT (MEMORYCHUNK_VALUE_BASEBIT + 30) + +/* A magic number for storing in the free bits of an external chunk */ +#define MEMORYCHUNK_MAGIC (UINT64CONST(0xB1A8DB858EB6EFBA) >> \ + MEMORYCHUNK_VALUE_BASEBIT << \ + MEMORYCHUNK_VALUE_BASEBIT) + +typedef struct MemoryChunk +{ +#ifdef MEMORY_CONTEXT_CHECKING + Size requested_size; +#endif + + /* bitfield for storing details about the chunk */ + uint64 hdrmask; /* must be last */ +} MemoryChunk; + +/* Get the MemoryChunk from the pointer */ +#define PointerGetMemoryChunk(p) ((MemoryChunk *) ((char *) (p) - sizeof(MemoryChunk))) +/* Get the pointer from the MemoryChunk */ +#define MemoryChunkGetPointer(c) ((void *) ((char *) (c) + sizeof(MemoryChunk))) + +/* private macros for making the inline functions below more simple */ +#define HdrMaskIsExternal(hdrmask) \ + ((hdrmask) & (1 << MEMORYCHUNK_EXTERNAL_BASEBIT)) +#define HdrMaskGetValue(hdrmask) \ + (((hdrmask) >> MEMORYCHUNK_VALUE_BASEBIT) & MEMORYCHUNK_MAX_VALUE) + +/* + * We should have used up all the bits here, so the compiler is likely to + * optimize out the & MEMORYCHUNK_MAX_BLOCKOFFSET. + */ +#define HdrMaskBlockOffset(hdrmask) \ + (((hdrmask) >> MEMORYCHUNK_BLOCKOFFSET_BASEBIT) & MEMORYCHUNK_MAX_BLOCKOFFSET) + +/* For external chunks only, check the magic number matches */ +#define HdrMaskCheckMagic(hdrmask) \ + (MEMORYCHUNK_MAGIC == \ + ((hdrmask) >> MEMORYCHUNK_VALUE_BASEBIT << MEMORYCHUNK_VALUE_BASEBIT)) +/* + * MemoryChunkSetHdrMask + * Store the given 'block', 'chunk_size' and 'methodid' in the given + * MemoryChunk. + * + * The number of bytes between 'block' and 'chunk' must be <= + * MEMORYCHUNK_MAX_BLOCKOFFSET. + * 'value' must be <= MEMORYCHUNK_MAX_VALUE. + */ +static inline void +MemoryChunkSetHdrMask(MemoryChunk *chunk, void *block, + Size value, MemoryContextMethodID methodid) +{ + Size blockoffset = (char *) chunk - (char *) block; + + Assert((char *) chunk > (char *) block); + Assert(blockoffset <= MEMORYCHUNK_MAX_BLOCKOFFSET); + Assert(value <= MEMORYCHUNK_MAX_VALUE); + Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK); + + chunk->hdrmask = (((uint64) blockoffset) << MEMORYCHUNK_BLOCKOFFSET_BASEBIT) | + (((uint64) value) << MEMORYCHUNK_VALUE_BASEBIT) | + methodid; +} + +/* + * MemoryChunkSetHdrMaskExternal + * Set 'chunk' as an externally managed chunk. Here we only record the + * MemoryContextMethodID and set the external chunk bit. + */ +static inline void +MemoryChunkSetHdrMaskExternal(MemoryChunk *chunk, + MemoryContextMethodID methodid) +{ + Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK); + + chunk->hdrmask = MEMORYCHUNK_MAGIC | (((uint64) 1) << MEMORYCHUNK_EXTERNAL_BASEBIT) | + methodid; +} + +/* + * MemoryChunkIsExternal + * Return true if 'chunk' is marked as external. + */ +static inline bool +MemoryChunkIsExternal(MemoryChunk *chunk) +{ + /* + * External chunks should always store MEMORYCHUNK_MAGIC in the upper + * portion of the hdrmask. + */ + Assert(!HdrMaskIsExternal(chunk->hdrmask) || + HdrMaskCheckMagic(chunk->hdrmask)); + + return HdrMaskIsExternal(chunk->hdrmask); +} + +/* + * MemoryChunkGetValue + * For non-external chunks, returns the value field as it was set in + * MemoryChunkSetHdrMask. + */ +static inline Size +MemoryChunkGetValue(MemoryChunk *chunk) +{ + Assert(!HdrMaskIsExternal(chunk->hdrmask)); + + return HdrMaskGetValue(chunk->hdrmask); +} + +/* + * MemoryChunkGetBlock + * For non-external chunks, returns the pointer to the block as was set + * in MemoryChunkSetHdrMask. + */ +static inline void * +MemoryChunkGetBlock(MemoryChunk *chunk) +{ + Assert(!HdrMaskIsExternal(chunk->hdrmask)); + + return (void *) ((char *) chunk - HdrMaskBlockOffset(chunk->hdrmask)); +} + +/* cleanup all internal definitions */ +#undef MEMORYCHUNK_EXTERNAL_BASEBIT +#undef MEMORYCHUNK_VALUE_BASEBIT +#undef MEMORYCHUNK_BLOCKOFFSET_BASEBIT +#undef MEMORYCHUNK_MAGIC +#undef HdrMaskIsExternal +#undef HdrMaskGetValue +#undef HdrMaskBlockOffset +#undef HdrMaskCheckMagic + +#endif /* MEMUTILS_MEMORYCHUNK_H */ diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index a4a4e356e5..51a3e719e6 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -57,6 +57,7 @@ AlenState Alias AllocBlock AllocChunk +AllocFreelistLink AllocPointer AllocSet AllocSetContext @@ -1522,12 +1523,14 @@ MemoizeKey MemoizePath MemoizeState MemoizeTuple +MemoryChunk MemoryContext MemoryContextCallback MemoryContextCallbackFunction MemoryContextCounters MemoryContextData MemoryContextMethods +MemoryContextMethodID MemoryStatsPrintFunc MergeAction MergeActionState -- 2.34.1
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-28 22:39  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-08-28 22:39 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Sun, 28 Aug 2022 at 23:04, David Rowley <dgrowleyml@gmail.com> wrote:
> I'll try that one again...

One more try to make CFbot happy.

David

Attachments:

v8-0001-Improve-performance-of-and-reduce-overheads-of-me.patch (text/plain, 104.4K) download From 118022b089279ea7a6b1d43ca9a105a3203905e3 Mon Sep 17 00:00:00 2001 From: David Rowley <dgrowley@gmail.com> Date: Thu, 9 Jun 2022 20:09:22 +1200 Subject: [PATCH v8] Improve performance of and reduce overheads of memory management Whenever we palloc a chunk of memory, traditionally, we prefix the returned pointer with a pointer to the memory context to which the chunk belongs. This is required so that we're able to easily determine the owning context when performing operations such as pfree() and repalloc(). For the AllocSet context, prior to this commit we additionally prefixed the pointer to the owning context with the size of the chunk. This made the header 16 bytes in size. This 16-byte overhead was required for all AllocSet allocations regardless of the allocation size. For the generation context, the problem was worse; in addition to the pointer to the owning context and chunk size, we also stored a pointer to the owning block so that we could track the number of freed chunks on a block. The slab allocator had a 16-byte chunk header. The changes being made here reduce the chunk header size down to just 8 bytes for all 3 of our memory context types. For small to medium sized allocations, this significantly increases the number of chunks that we can fit on a given block which results in much more efficient use of memory. Additionally, this commit completely changes the rule that pointers to palloc'd memory must be directly prefixed by a pointer to the owning memory context and instead, we now insist that they're directly prefixed by an 8-byte value where the least significant 3-bits are set to a value to indicate which type of memory context the pointer belongs to. Using those 3 bits as an index (known as MemoryContextMethodID) to a new array which stores the methods for each memory context type, we're now able to pass the pointer given to functions such as pfree() and repalloc() to the function specific to that context implementation to allow them to devise their own methods of finding the memory context which owns the given allocated chunk of memory. The reason we're able to reduce the chunk header down to just 8 bytes is because of the way we make use of the remaining 61 bits of the required 8-byte chunk header. Here we also implement a general-purpose MemoryChunk struct which makes use of those 61 remaining bits to allow the storage of a 30-bit value which the MemoryContext is free to use as it pleases, and also the number of bytes which must be subtracted from the chunk to get a reference to the block that the chunk is stored on (also 30 bits). The 1 additional remaining bit is to denote if the chunk is an "external" chunk or not. External here means that the chunk header does not store the 30-bit value or the block offset. The MemoryContext can use these external chunks at any time, but must use them if any of the two 30-bit fields are not large enough for the value(s) that need to be stored in them. When the chunk is marked as external, it is up to the MemoryContext to devise its own means to determine the block offset. Using 3-bits for the MemoryContextMethodID does mean we're limiting ourselves to only having a maximum of 8 different memory context types. We could reduce the bit space for the 30-bit value a little to make way for more than 3 bits, but it seems like it might be better to do that only if we ever need more than 8 context types. This would only be a problem if some future memory context type which does not use MemoryChunk really couldn't give up any of the 61 remaining bits in the chunk header. With this MemoryChunk, each of our 3 memory context types can quickly obtain a reference to the block any given chunk is located on. AllocSet is able to find the context to which the chunk is owned by first obtaining a reference to the block by subtracting the block offset as is stored in the 'hdrmask' field and then referencing the block's 'aset' field. The Generation context uses the same method, but GenerationBlock did not have a field pointing back to the owning context, so one is added by this commit. In aset.c and generation.c, all allocations larger than allocChunkLimit are stored on dedicated blocks. When there's just a single chunk on a block like this, it's easy to find the block from the chunk, we just subtract the size of the block header from the chunk pointer. The size of these chunks is also known as we store the endptr on the block, so we can just subtract the pointer to the allocated memory from that. Because we can easily find the owning block and the size of the chunk for these dedicated blocks, we just always use external chunks for allocation sizes larger than allocChunkLimit. For geneartion.c, this sidesteps the problem of non-external MemoryChunks being unable to represent chunk sizes >= 1GB. This is less of a problem for aset.c as we store the freelist index in the MemoryChunk's spare 30-bit field. we can easily reverse engineer the chunk size from this when needed. Storing this saves AllocSetFree() from having to make a call to AllocSetFreeIndex() to determine which freelist to put the newly freed chunk on. For the slab allocator, this commit adds a new restriction that slab chunks cannot be >= 1GB in size. If there happened to be any users of slab.c which used chunk sizes this large, they really should be using AllocSet instead. Here we also add a restriction that normal non-dedicated blocks cannot be 1GB or larger. It's now not possible to pass a 'maxBlockSize' >= 1GB during the creation of an AllocSet or Generation context. Allocations can still be larger than 1GB, it's just these will always be on dedicated blocks (which are not restricted to 1GB in size). Author: Andres Freund, David Rowley Discussion: https://postgr.es/m/CAApHDvpjauCRXcgcaL6+e3eqecEHoeRm9D-kcbuvBitgPnW=vw@mail.gmail.com --- src/backend/utils/mmgr/README | 60 ++- src/backend/utils/mmgr/aset.c | 507 +++++++++++++---------- src/backend/utils/mmgr/generation.c | 351 ++++++++-------- src/backend/utils/mmgr/mcxt.c | 91 +++- src/backend/utils/mmgr/slab.c | 197 ++++----- src/include/nodes/memnodes.h | 7 +- src/include/utils/memutils.h | 51 +-- src/include/utils/memutils_internal.h | 130 ++++++ src/include/utils/memutils_memorychunk.h | 231 +++++++++++ src/tools/pgindent/typedefs.list | 3 + 10 files changed, 1034 insertions(+), 594 deletions(-) create mode 100644 src/include/utils/memutils_internal.h create mode 100644 src/include/utils/memutils_memorychunk.h diff --git a/src/backend/utils/mmgr/README b/src/backend/utils/mmgr/README index 777481c83d..cd6228b0e2 100644 --- a/src/backend/utils/mmgr/README +++ b/src/backend/utils/mmgr/README @@ -384,35 +384,55 @@ MemoryContext like the parent and child contexts, and the name of the context. This is essentially an abstract superclass, and the behavior is -determined by the "methods" pointer is its virtual function table -(struct MemoryContextMethods). Specific memory context types will use -derived structs having these fields as their first fields. All the +determined by the "methods" pointer which references which set of +MemoryContextMethods are to be used. Specific memory context types will +use derived structs having these fields as their first fields. All the contexts of a specific type will have methods pointers that point to -the same static table of function pointers. +the corresponding element in the mcxt_methods[] array as defined in mcxt.c. While operations like allocating from and resetting a context take the relevant MemoryContext as a parameter, operations like free and realloc are trickier. To make those work, we require all memory context types to produce allocated chunks that are immediately, -without any padding, preceded by a pointer to the corresponding -MemoryContext. +without any padding, preceded by a uint64 value of which the least +significant 3 bits are set to the owning context's MemoryContextMethodID. +This allows the code to determine the correct MemoryContextMethods to +use by looking up the mcxt_methods[] array using the 3 bits as an index +into that array. If a type of allocator needs additional information about its chunks, like e.g. the size of the allocation, that information can in turn -precede the MemoryContext. This means the only overhead implied by -the memory context mechanism is a pointer to its context, so we're not -constraining context-type designers very much. - -Given this, routines like pfree determine their corresponding context -with an operation like (although that is usually encapsulated in -GetMemoryChunkContext()) - - MemoryContext context = *(MemoryContext*) (((char *) pointer) - sizeof(void *)); - -and then invoke the corresponding method for the context - - context->methods->free_p(pointer); - +either be encoded into the remaining 61 bits of the preceding uint64 value +or if more space is required, additional values may be stored directly prior +to the uint64 value. It is up to the context implementation to manage this. + +Given this, routines like pfree can determine which set of +MemoryContextMethods to call the free_p function for by calling +GetMemoryChunkMethodID() and finding the corresponding MemoryContextMethods +in the mcxt_methods array[]. For convenience, the MCXT_METHOD() macro is +provided, making the code as simple as: + +void +pfree(void *pointer) +{ + MCXT_METHOD(pointer, free_p)(pointer); +} + +All of the current memory contexts make use of the MemoryChunk header type +which is defined in memutils_memorychunk.h. This suits all of the existing +context types well as it makes use of the remaining 61-bits of the uint64 +header to efficiently encode the size of the chunk of memory (or freelist +index, in the case of aset.c) and the number of bytes which must be subtracted +from the chunk in order to obtain a reference to the block that the chunk +belongs to. 30 bits are used for each of these. If more than 30 bits are +required then the memory context must manage that itself. This can be done by +calling the MemoryChunkSetHdrMaskExternal() function on the given chunk. +Currently, each memory context type stores large allocations on dedicated +blocks (which always contain only a single chunk). For these, finding the +block is simple as we know that the chunk must be the first on the given +block, so the block is always at a fixed offset to the chunk. For these, +finding the size of the chunk is also simple as the block always stores an +endptr which we can use to calculate the size of the chunk. More Control Over aset.c Behavior --------------------------------- diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index ec3e264a73..285a908e4a 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -49,6 +49,8 @@ #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" /*-------------------- * Chunk freelist k holds chunks of size 1 << (k + ALLOC_MINBITS), @@ -66,7 +68,9 @@ * CAUTION: ALLOC_MINBITS must be large enough so that * 1<<ALLOC_MINBITS is at least MAXALIGN, * or we may fail to align the smallest chunks adequately. - * 8-byte alignment is enough on all currently known machines. + * 8-byte alignment is enough on all currently known machines. This 8-byte + * minimum also allows us to store a pointer to the next freelist item within + * the chunk of memory itself. * * With the current parameters, request sizes up to 8K are treated as chunks, * larger requests go into dedicated blocks. Change ALLOCSET_NUM_FREELISTS @@ -98,10 +102,9 @@ */ #define ALLOC_BLOCKHDRSZ MAXALIGN(sizeof(AllocBlockData)) -#define ALLOC_CHUNKHDRSZ sizeof(struct AllocChunkData) +#define ALLOC_CHUNKHDRSZ sizeof(MemoryChunk) typedef struct AllocBlockData *AllocBlock; /* forward reference */ -typedef struct AllocChunkData *AllocChunk; /* * AllocPointer @@ -109,6 +112,33 @@ typedef struct AllocChunkData *AllocChunk; */ typedef void *AllocPointer; +/* + * AllocFreelistLink + * When pfreeing memory, if we maintain a freelist for the given chunk's + * size then we use a AllocFreelistLink to point to the current item in + * the AllocSetContext's freelist and then set the given freelist element + * to point to the chunk being freed. + */ +typedef struct AllocFreelistLink +{ + MemoryChunk *next; +} AllocFreelistLink; + +/* + * Obtain a AllocFreelistLink for the given chunk. Allocation sizes are + * always at least sizeof(AllocFreelistLink), so we reuse the pointer's memory + * itself to store the freelist link. To make it less likely that any write + * after pfree() bugs corrupt this, we put the link at the very end of the + * allocated chunk. + */ +#define GetFreeListLink(chkptr, chksz) \ + (AllocFreelistLink *) ((char *) (chkptr) + ALLOC_CHUNKHDRSZ + \ + (chksz) - sizeof(AllocFreelistLink)) + +/* Determine the size of the chunk based on the freelist index */ +#define GetChunkSizeFromFreelistIdx(fidx) \ + ((((Size) 1) << ALLOC_MINBITS) << (fidx)) + /* * AllocSetContext is our standard implementation of MemoryContext. * @@ -123,7 +153,7 @@ typedef struct AllocSetContext MemoryContextData header; /* Standard memory-context fields */ /* Info about storage allocated in this context: */ AllocBlock blocks; /* head of list of blocks in this set */ - AllocChunk freelist[ALLOCSET_NUM_FREELISTS]; /* free chunk lists */ + MemoryChunk *freelist[ALLOCSET_NUM_FREELISTS]; /* free chunk lists */ /* Allocation parameters for this context: */ Size initBlockSize; /* initial block size */ Size maxBlockSize; /* maximum block size */ @@ -139,8 +169,8 @@ typedef AllocSetContext *AllocSet; /* * AllocBlock * An AllocBlock is the unit of memory that is obtained by aset.c - * from malloc(). It contains one or more AllocChunks, which are - * the units requested by palloc() and freed by pfree(). AllocChunks + * from malloc(). It contains one or more MemoryChunks, which are + * the units requested by palloc() and freed by pfree(). MemoryChunks * cannot be returned to malloc() individually, instead they are put * on freelists by pfree() and re-used by the next palloc() that has * a matching request size. @@ -158,48 +188,12 @@ typedef struct AllocBlockData } AllocBlockData; /* - * AllocChunk - * The prefix of each piece of memory in an AllocBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "aset" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). We simplify matters for this - * module by requiring sizeof(AllocChunkData) to be maxaligned, and then - * we can ensure things work by adding any required alignment padding before - * the "aset" field. There is a static assertion below that the alignment - * is done correctly. - */ -typedef struct AllocChunkData -{ - /* size is always the size of the usable space in the chunk */ - Size size; -#ifdef MEMORY_CONTEXT_CHECKING - /* when debugging memory usage, also store actual requested size */ - /* this is zero in a free chunk */ - Size requested_size; - -#define ALLOCCHUNK_RAWSIZE (SIZEOF_SIZE_T * 2 + SIZEOF_VOID_P) -#else -#define ALLOCCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P) -#endif /* MEMORY_CONTEXT_CHECKING */ - - /* ensure proper alignment by adding padding if needed */ -#if (ALLOCCHUNK_RAWSIZE % MAXIMUM_ALIGNOF) != 0 - char padding[MAXIMUM_ALIGNOF - ALLOCCHUNK_RAWSIZE % MAXIMUM_ALIGNOF]; -#endif - - /* aset is the owning aset if allocated, or the freelist link if free */ - void *aset; - /* there must not be any padding to reach a MAXALIGN boundary here! */ -} AllocChunkData; - -/* - * Only the "aset" field should be accessed outside this module. + * Only the "hdrmask" field should be accessed outside this module. * We keep the rest of an allocated chunk's header marked NOACCESS when using * valgrind. But note that chunk headers that are in a freelist are kept * accessible, for simplicity. */ -#define ALLOCCHUNK_PRIVATE_LEN offsetof(AllocChunkData, aset) +#define ALLOCCHUNK_PRIVATE_LEN offsetof(MemoryChunk, hdrmask) /* * AllocPointerIsValid @@ -213,10 +207,12 @@ typedef struct AllocChunkData */ #define AllocSetIsValid(set) PointerIsValid(set) -#define AllocPointerGetChunk(ptr) \ - ((AllocChunk)(((char *)(ptr)) - ALLOC_CHUNKHDRSZ)) -#define AllocChunkGetPointer(chk) \ - ((AllocPointer)(((char *)(chk)) + ALLOC_CHUNKHDRSZ)) +/* + * We always store external chunks on a dedicated block. This makes fetching + * the block from an external chunk easy since it's always the first and only + * chunk on the block. + */ +#define ExternalChunkGetBlock(chunk) (AllocBlock) ((char *) chunk - ALLOC_BLOCKHDRSZ) /* * Rather than repeatedly creating and deleting memory contexts, we keep some @@ -260,42 +256,6 @@ static AllocSetFreeList context_freelists[2] = } }; -/* - * These functions implement the MemoryContext API for AllocSet contexts. - */ -static void *AllocSetAlloc(MemoryContext context, Size size); -static void AllocSetFree(MemoryContext context, void *pointer); -static void *AllocSetRealloc(MemoryContext context, void *pointer, Size size); -static void AllocSetReset(MemoryContext context); -static void AllocSetDelete(MemoryContext context); -static Size AllocSetGetChunkSpace(MemoryContext context, void *pointer); -static bool AllocSetIsEmpty(MemoryContext context); -static void AllocSetStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); - -#ifdef MEMORY_CONTEXT_CHECKING -static void AllocSetCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for AllocSet contexts. - */ -static const MemoryContextMethods AllocSetMethods = { - AllocSetAlloc, - AllocSetFree, - AllocSetRealloc, - AllocSetReset, - AllocSetDelete, - AllocSetGetChunkSpace, - AllocSetIsEmpty, - AllocSetStats -#ifdef MEMORY_CONTEXT_CHECKING - ,AllocSetCheck -#endif -}; - /* ---------- * AllocSetFreeIndex - @@ -387,18 +347,24 @@ AllocSetContextCreateInternal(MemoryContext parent, AllocSet set; AllocBlock block; - /* Assert we padded AllocChunkData properly */ + /* ensure MemoryChunk's size is properly maxaligned */ StaticAssertStmt(ALLOC_CHUNKHDRSZ == MAXALIGN(ALLOC_CHUNKHDRSZ), - "sizeof(AllocChunkData) is not maxaligned"); - StaticAssertStmt(offsetof(AllocChunkData, aset) + sizeof(MemoryContext) == - ALLOC_CHUNKHDRSZ, - "padding calculation in AllocChunkData is wrong"); + "sizeof(MemoryChunk) is not maxaligned"); + /* check we have enough space to store the freelist link */ + StaticAssertStmt(sizeof(AllocFreelistLink) <= (1 << ALLOC_MINBITS), + "sizeof(AllocFreelistLink) larger than minimum allocation size"); /* * First, validate allocation parameters. Once these were regular runtime * test and elog's, but in practice Asserts seem sufficient because nobody * varies their parameters at runtime. We somewhat arbitrarily enforce a - * minimum 1K block size. + * minimum 1K block size. We restrict the maximum block size to + * MEMORYCHUNK_MAX_BLOCKOFFSET as MemoryChunks are limited to this in + * regards to addressing the offset between the chunk and the block that + * the chunk is stored on. We would be unable to store the offset between + * the chunk and block for any chunks that were beyond + * MEMORYCHUNK_MAX_BLOCKOFFSET bytes into the block if the block was to be + * larger than this. */ Assert(initBlockSize == MAXALIGN(initBlockSize) && initBlockSize >= 1024); @@ -409,6 +375,7 @@ AllocSetContextCreateInternal(MemoryContext parent, (minContextSize == MAXALIGN(minContextSize) && minContextSize >= 1024 && minContextSize <= maxBlockSize)); + Assert(maxBlockSize <= MEMORYCHUNK_MAX_BLOCKOFFSET); /* * Check whether the parameters match either available freelist. We do @@ -443,7 +410,7 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Reinitialize its header, installing correct name and parent */ MemoryContextCreate((MemoryContext) set, T_AllocSetContext, - &AllocSetMethods, + MCTX_ASET_ID, parent, name); @@ -519,7 +486,8 @@ AllocSetContextCreateInternal(MemoryContext parent, * * We have to have allocChunkLimit a power of two, because the requested * and actually-allocated sizes of any chunk must be on the same side of - * the limit, else we get confused about whether the chunk is "big". + * the limit, else we get confused about whether the chunk is on a + * dedicated block. * * Also, allocChunkLimit must not exceed ALLOCSET_SEPARATE_THRESHOLD. */ @@ -534,7 +502,7 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) set, T_AllocSetContext, - &AllocSetMethods, + MCTX_ASET_ID, parent, name); @@ -555,7 +523,7 @@ AllocSetContextCreateInternal(MemoryContext parent, * thrash malloc() when a context is repeatedly reset after small allocations, * which is typical behavior for per-tuple contexts. */ -static void +void AllocSetReset(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -623,7 +591,7 @@ AllocSetReset(MemoryContext context) * * Unlike AllocSetReset, this *must* free all resources of the set. */ -static void +void AllocSetDelete(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -717,12 +685,12 @@ AllocSetDelete(MemoryContext context) * is marked, as mcxt.c will set it to UNDEFINED. In some paths we will * return space that is marked NOACCESS - AllocSetRealloc has to beware! */ -static void * +void * AllocSetAlloc(MemoryContext context, Size size) { AllocSet set = (AllocSet) context; AllocBlock block; - AllocChunk chunk; + MemoryChunk *chunk; int fidx; Size chunk_size; Size blksize; @@ -746,18 +714,20 @@ AllocSetAlloc(MemoryContext context, Size size) block->aset = set; block->freeptr = block->endptr = ((char *) block) + blksize; - chunk = (AllocChunk) (((char *) block) + ALLOC_BLOCKHDRSZ); - chunk->aset = set; - chunk->size = chunk_size; + chunk = (MemoryChunk *) (((char *) block) + ALLOC_BLOCKHDRSZ); + + /* mark the MemoryChunk as externally managed */ + MemoryChunkSetHdrMaskExternal(chunk, MCTX_ASET_ID); + #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk_size) - set_sentinel(AllocChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* @@ -780,13 +750,13 @@ AllocSetAlloc(MemoryContext context, Size size) } /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -799,37 +769,43 @@ AllocSetAlloc(MemoryContext context, Size size) chunk = set->freelist[fidx]; if (chunk != NULL) { - Assert(chunk->size >= size); + AllocFreelistLink *link; - set->freelist[fidx] = (AllocChunk) chunk->aset; + Assert(fidx == MemoryChunkGetValue(chunk)); - chunk->aset = (void *) set; + chunk_size = GetChunkSizeFromFreelistIdx(fidx); + link = GetFreeListLink(chunk, chunk_size); + + /* pop this chunk off the freelist */ + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + set->freelist[fidx] = link->next; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(AllocChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, - chunk->size - size); + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, + chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * Choose the actual chunk size to allocate. */ - chunk_size = (1 << ALLOC_MINBITS) << fidx; + chunk_size = GetChunkSizeFromFreelistIdx(fidx); Assert(chunk_size >= size); /* @@ -856,6 +832,7 @@ AllocSetAlloc(MemoryContext context, Size size) */ while (availspace >= ((1 << ALLOC_MINBITS) + ALLOC_CHUNKHDRSZ)) { + AllocFreelistLink *link; Size availchunk = availspace - ALLOC_CHUNKHDRSZ; int a_fidx = AllocSetFreeIndex(availchunk); @@ -864,29 +841,34 @@ AllocSetAlloc(MemoryContext context, Size size) * freelist than the one we need to put this chunk on. The * exception is when availchunk is exactly a power of 2. */ - if (availchunk != ((Size) 1 << (a_fidx + ALLOC_MINBITS))) + if (availchunk != GetChunkSizeFromFreelistIdx(a_fidx)) { a_fidx--; Assert(a_fidx >= 0); - availchunk = ((Size) 1 << (a_fidx + ALLOC_MINBITS)); + availchunk = GetChunkSizeFromFreelistIdx(a_fidx); } - chunk = (AllocChunk) (block->freeptr); + chunk = (MemoryChunk *) (block->freeptr); /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, ALLOC_CHUNKHDRSZ); - block->freeptr += (availchunk + ALLOC_CHUNKHDRSZ); availspace -= (availchunk + ALLOC_CHUNKHDRSZ); - chunk->size = availchunk; + /* store the freelist index in the value field */ + MemoryChunkSetHdrMask(chunk, block, a_fidx, MCTX_ASET_ID); #ifdef MEMORY_CONTEXT_CHECKING - chunk->requested_size = 0; /* mark it free */ + chunk->requested_size = InvalidAllocSize; /* mark it free */ #endif - chunk->aset = (void *) set->freelist[a_fidx]; + /* push this chunk onto the freelist */ + link = GetFreeListLink(chunk, availchunk); + + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + link->next = set->freelist[a_fidx]; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); + set->freelist[a_fidx] = chunk; } - /* Mark that we need to create a new block */ block = NULL; } @@ -954,7 +936,7 @@ AllocSetAlloc(MemoryContext context, Size size) /* * OK, do the allocation */ - chunk = (AllocChunk) (block->freeptr); + chunk = (MemoryChunk *) (block->freeptr); /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, ALLOC_CHUNKHDRSZ); @@ -962,67 +944,68 @@ AllocSetAlloc(MemoryContext context, Size size) block->freeptr += (chunk_size + ALLOC_CHUNKHDRSZ); Assert(block->freeptr <= block->endptr); - chunk->aset = (void *) set; - chunk->size = chunk_size; + /* store the freelist index in the value field */ + MemoryChunkSetHdrMask(chunk, block, fidx, MCTX_ASET_ID); + #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(AllocChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) AllocChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) AllocChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return AllocChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * AllocSetFree * Frees allocated memory; memory is removed from the set. */ -static void -AllocSetFree(MemoryContext context, void *pointer) +void +AllocSetFree(void *pointer) { - AllocSet set = (AllocSet) context; - AllocChunk chunk = AllocPointerGetChunk(pointer); + AllocSet set; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); + if (MemoryChunkIsExternal(chunk)) + { + + AllocBlock block = ExternalChunkGetBlock(chunk); + + set = block->aset; + #ifdef MEMORY_CONTEXT_CHECKING - /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunk->size) - if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", - set->header.name, chunk); + { + Size chunk_size = block->endptr - (char *) pointer; + + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < chunk_size) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); + } #endif - if (chunk->size > set->allocChunkLimit) - { - /* - * Big chunks are certain to have been allocated as single-chunk - * blocks. Just unlink that block and return it to malloc(). - */ - AllocBlock block = (AllocBlock) (((char *) chunk) - ALLOC_BLOCKHDRSZ); /* - * Try to verify that we have a sane block pointer: it should - * reference the correct aset, and freeptr and endptr should point - * just past the chunk. + * Try to verify that we have a sane block pointer, the freeptr should + * match the endptr. */ - if (block->aset != set || - block->freeptr != block->endptr || - block->freeptr != ((char *) block) + - (chunk->size + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) + if (block->freeptr != block->endptr) elog(ERROR, "could not find block containing chunk %p", chunk); /* OK, remove block from aset's list and free it */ @@ -1033,7 +1016,7 @@ AllocSetFree(MemoryContext context, void *pointer) if (block->next) block->next->prev = block->prev; - context->mem_allocated -= block->endptr - ((char *) block); + set->header.mem_allocated -= block->endptr - ((char *) block); #ifdef CLOBBER_FREED_MEMORY wipe_mem(block, block->freeptr - ((char *) block)); @@ -1042,20 +1025,39 @@ AllocSetFree(MemoryContext context, void *pointer) } else { - /* Normal case, put the chunk into appropriate freelist */ - int fidx = AllocSetFreeIndex(chunk->size); + int fidx = MemoryChunkGetValue(chunk); + AllocBlock block = MemoryChunkGetBlock(chunk); + Size chunk_size = GetChunkSizeFromFreelistIdx(fidx); + AllocFreelistLink *link = GetFreeListLink(chunk, chunk_size); - chunk->aset = (void *) set->freelist[fidx]; + set = block->aset; + +#ifdef MEMORY_CONTEXT_CHECKING + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < chunk_size) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); +#endif #ifdef CLOBBER_FREED_MEMORY - wipe_mem(pointer, chunk->size); + wipe_mem(pointer, chunk_size); #endif + /* Normal case, put the chunk into appropriate freelist */ + /* push this chunk onto the top of the freelist for this chunk size */ + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + link->next = set->freelist[fidx]; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); + set->freelist[fidx] = chunk; #ifdef MEMORY_CONTEXT_CHECKING - /* Reset requested_size to 0 in chunks that are on freelist */ - chunk->requested_size = 0; + + /* + * Reset requested_size to InvalidAllocSize in chunks that are on + * freelist. + */ + chunk->requested_size = InvalidAllocSize; #endif - set->freelist[fidx] = chunk; } } @@ -1071,57 +1073,48 @@ AllocSetFree(MemoryContext context, void *pointer) * (In principle, we could use VALGRIND_GET_VBITS() to rediscover the old * request size.) */ -static void * -AllocSetRealloc(MemoryContext context, void *pointer, Size size) +void * +AllocSetRealloc(void *pointer, Size size) { - AllocSet set = (AllocSet) context; - AllocChunk chunk = AllocPointerGetChunk(pointer); + AllocBlock block; + AllocSet set; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); Size oldsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - oldsize = chunk->size; - -#ifdef MEMORY_CONTEXT_CHECKING - /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < oldsize) - if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", - set->header.name, chunk); -#endif - - if (oldsize > set->allocChunkLimit) + if (MemoryChunkIsExternal(chunk)) { /* * The chunk must have been allocated as a single-chunk block. Use * realloc() to make the containing block bigger, or smaller, with * minimum space wastage. */ - AllocBlock block = (AllocBlock) (((char *) chunk) - ALLOC_BLOCKHDRSZ); Size chksize; Size blksize; Size oldblksize; + block = ExternalChunkGetBlock(chunk); + oldsize = block->endptr - (char *) pointer; + set = block->aset; + +#ifdef MEMORY_CONTEXT_CHECKING + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < oldsize) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); +#endif + /* - * Try to verify that we have a sane block pointer: it should - * reference the correct aset, and freeptr and endptr should point - * just past the chunk. + * Try to verify that we have a sane block pointer, the freeptr should + * match the endptr. */ - if (block->aset != set || - block->freeptr != block->endptr || - block->freeptr != ((char *) block) + - (oldsize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) + if (block->freeptr != block->endptr) elog(ERROR, "could not find block containing chunk %p", chunk); - /* - * Even if the new request is less than set->allocChunkLimit, we stick - * with the single-chunk block approach. Therefore we need - * chunk->size to be bigger than set->allocChunkLimit, so we don't get - * confused about the chunk's status in future calls. - */ - chksize = Max(size, set->allocChunkLimit + 1); - chksize = MAXALIGN(chksize); + chksize = MAXALIGN(size); /* Do the realloc */ blksize = chksize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ; @@ -1136,21 +1129,20 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) } /* updated separately, not to underflow when (oldblksize > blksize) */ - context->mem_allocated -= oldblksize; - context->mem_allocated += blksize; + set->header.mem_allocated -= oldblksize; + set->header.mem_allocated += blksize; block->freeptr = block->endptr = ((char *) block) + blksize; /* Update pointers since block has likely been moved */ - chunk = (AllocChunk) (((char *) block) + ALLOC_BLOCKHDRSZ); - pointer = AllocChunkGetPointer(chunk); + chunk = (MemoryChunk *) (((char *) block) + ALLOC_BLOCKHDRSZ); + pointer = MemoryChunkGetPointer(chunk); if (block->prev) block->prev->next = block; else set->blocks = block; if (block->next) block->next->prev = block; - chunk->size = chksize; #ifdef MEMORY_CONTEXT_CHECKING #ifdef RANDOMIZE_ALLOCATED_MEMORY @@ -1172,9 +1164,8 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) #endif chunk->requested_size = size; - /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) + if (size < chksize) set_sentinel(pointer, size); #else /* !MEMORY_CONTEXT_CHECKING */ @@ -1195,12 +1186,24 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) return pointer; } + block = MemoryChunkGetBlock(chunk); + oldsize = GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)); + set = block->aset; + +#ifdef MEMORY_CONTEXT_CHECKING + /* Test for someone scribbling on unused space in chunk */ + if (chunk->requested_size < oldsize) + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); +#endif + /* * Chunk sizes are aligned to power of 2 in AllocSetAlloc(). Maybe the * allocated area already is >= the new size. (In particular, we will * fall out here if the requested size is a decrease.) */ - else if (oldsize >= size) + if (oldsize >= size) { #ifdef MEMORY_CONTEXT_CHECKING Size oldrequest = chunk->requested_size; @@ -1289,34 +1292,59 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) memcpy(newPointer, pointer, oldsize); /* free old chunk */ - AllocSetFree((MemoryContext) set, pointer); + AllocSetFree(pointer); return newPointer; } } +/* + * AllocSetGetChunkContext + * Return the MemoryContext that 'pointer' belongs to. + */ +MemoryContext +AllocSetGetChunkContext(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + AllocBlock block; + AllocSet set; + + if (MemoryChunkIsExternal(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (AllocBlock) MemoryChunkGetBlock(chunk); + + set = block->aset; + + return &set->header; +} + /* * AllocSetGetChunkSpace * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -AllocSetGetChunkSpace(MemoryContext context, void *pointer) +Size +AllocSetGetChunkSpace(void *pointer) { - AllocChunk chunk = AllocPointerGetChunk(pointer); - Size result; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); - VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - result = chunk->size + ALLOC_CHUNKHDRSZ; - VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); - return result; + if (MemoryChunkIsExternal(chunk)) + { + AllocBlock block = ExternalChunkGetBlock(chunk); + + return block->endptr - (char *) chunk; + } + + return GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)) + + ALLOC_CHUNKHDRSZ; } /* * AllocSetIsEmpty * Is an allocset empty of any allocated space? */ -static bool +bool AllocSetIsEmpty(MemoryContext context) { /* @@ -1339,7 +1367,7 @@ AllocSetIsEmpty(MemoryContext context) * totals: if not NULL, add stats about this context into *totals. * print_to_stderr: print stats to stderr if true, elog otherwise. */ -static void +void AllocSetStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr) @@ -1363,13 +1391,21 @@ AllocSetStats(MemoryContext context, } for (fidx = 0; fidx < ALLOCSET_NUM_FREELISTS; fidx++) { - AllocChunk chunk; + MemoryChunk *chunk = set->freelist[fidx]; - for (chunk = set->freelist[fidx]; chunk != NULL; - chunk = (AllocChunk) chunk->aset) + while (chunk != NULL) { + Size chksz = GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)); + AllocFreelistLink *link = GetFreeListLink(chunk, chksz); + + Assert(GetChunkSizeFromFreelistIdx(fidx) == chksz); + freechunks++; - freespace += chunk->size + ALLOC_CHUNKHDRSZ; + freespace += chksz + ALLOC_CHUNKHDRSZ; + + VALGRIND_MAKE_MEM_DEFINED(link, sizeof(AllocFreelistLink)); + chunk = link->next; + VALGRIND_MAKE_MEM_NOACCESS(link, sizeof(AllocFreelistLink)); } } @@ -1404,7 +1440,7 @@ AllocSetStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void AllocSetCheck(MemoryContext context) { AllocSet set = (AllocSet) context; @@ -1421,6 +1457,7 @@ AllocSetCheck(MemoryContext context) long blk_used = block->freeptr - bpoz; long blk_data = 0; long nchunks = 0; + bool has_external_chunk = false; if (set->keeper == block) total_allocated += block->endptr - ((char *) set); @@ -1452,20 +1489,31 @@ AllocSetCheck(MemoryContext context) */ while (bpoz < block->freeptr) { - AllocChunk chunk = (AllocChunk) bpoz; + MemoryChunk *chunk = (MemoryChunk *) bpoz; + AllocBlock chunkblock; Size chsize, dsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); - chsize = chunk->size; /* aligned chunk size */ + if (MemoryChunkIsExternal(chunk)) + { + chsize = block->endptr - (char *) MemoryChunkGetPointer(chunk); /* aligned chunk size */ + chunkblock = ExternalChunkGetBlock(chunk); + has_external_chunk = true; + } + else + { + chsize = GetChunkSizeFromFreelistIdx(MemoryChunkGetValue(chunk)); /* aligned chunk size */ + chunkblock = (AllocBlock) MemoryChunkGetBlock(chunk); + } dsize = chunk->requested_size; /* real data */ /* * Check chunk size */ - if (dsize > chsize) + if (dsize != InvalidAllocSize && dsize > chsize) elog(WARNING, "problem in alloc set %s: req size > alloc size for chunk %p in block %p", name, chunk, block); if (chsize < (1 << ALLOC_MINBITS)) @@ -1478,20 +1526,15 @@ AllocSetCheck(MemoryContext context) elog(WARNING, "problem in alloc set %s: bad single-chunk %p in block %p", name, chunk, block); - /* - * If chunk is allocated, check for correct aset pointer. (If it's - * free, the aset is the freelist pointer, which we can't check as - * easily...) Note this is an incomplete test, since palloc(0) - * produces an allocated chunk with requested_size == 0. - */ - if (dsize > 0 && chunk->aset != (void *) set) - elog(WARNING, "problem in alloc set %s: bogus aset link in block %p, chunk %p", - name, block, chunk); + /* Check the block offset correctly matches this block */ + if (block != chunkblock) + elog(WARNING, "problem in alloc set %s: bad block offset for chunk %p in block %p", + name, chunk, block); /* * Check for overwrite of padding space in an allocated chunk. */ - if (chunk->aset == (void *) set && dsize < chsize && + if (dsize != InvalidAllocSize && dsize < chsize && !sentinel_ok(chunk, ALLOC_CHUNKHDRSZ + dsize)) elog(WARNING, "problem in alloc set %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); @@ -1500,7 +1543,7 @@ AllocSetCheck(MemoryContext context) * If chunk is allocated, disallow external access to private part * of chunk header. */ - if (chunk->aset == (void *) set) + if (dsize != InvalidAllocSize) VALGRIND_MAKE_MEM_NOACCESS(chunk, ALLOCCHUNK_PRIVATE_LEN); blk_data += chsize; @@ -1512,6 +1555,10 @@ AllocSetCheck(MemoryContext context) if ((blk_data + (nchunks * ALLOC_CHUNKHDRSZ)) != blk_used) elog(WARNING, "problem in alloc set %s: found inconsistent memory block %p", name, block); + + if (has_external_chunk && nchunks > 1) + elog(WARNING, "problem in alloc set %s: external chunk on non-dedicated block %p", + name, block); } Assert(total_allocated == context->mem_allocated); diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index e530e272e0..eac3079823 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -39,15 +39,16 @@ #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" #define Generation_BLOCKHDRSZ MAXALIGN(sizeof(GenerationBlock)) -#define Generation_CHUNKHDRSZ sizeof(GenerationChunk) +#define Generation_CHUNKHDRSZ sizeof(MemoryChunk) #define Generation_CHUNK_FRACTION 8 typedef struct GenerationBlock GenerationBlock; /* forward reference */ -typedef struct GenerationChunk GenerationChunk; typedef void *GenerationPointer; @@ -89,6 +90,7 @@ typedef struct GenerationContext struct GenerationBlock { dlist_node node; /* doubly-linked list of blocks */ + GenerationContext *context; /* pointer back to the owning context */ Size blksize; /* allocated size of this block */ int nchunks; /* number of chunks in the block */ int nfree; /* number of free chunks */ @@ -97,104 +99,36 @@ struct GenerationBlock }; /* - * GenerationChunk - * The prefix of each piece of memory in a GenerationBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "context" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). We simplify matters for this - * module by requiring sizeof(GenerationChunk) to be maxaligned, and then - * we can ensure things work by adding any required alignment padding before - * the pointer fields. There is a static assertion below that the alignment - * is done correctly. - */ -struct GenerationChunk -{ - /* size is always the size of the usable space in the chunk */ - Size size; -#ifdef MEMORY_CONTEXT_CHECKING - /* when debugging memory usage, also store actual requested size */ - /* this is zero in a free chunk */ - Size requested_size; - -#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T * 2 + SIZEOF_VOID_P * 2) -#else -#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P * 2) -#endif /* MEMORY_CONTEXT_CHECKING */ - - /* ensure proper alignment by adding padding if needed */ -#if (GENERATIONCHUNK_RAWSIZE % MAXIMUM_ALIGNOF) != 0 - char padding[MAXIMUM_ALIGNOF - GENERATIONCHUNK_RAWSIZE % MAXIMUM_ALIGNOF]; -#endif - - GenerationBlock *block; /* block owning this chunk */ - GenerationContext *context; /* owning context, or NULL if freed chunk */ - /* there must not be any padding to reach a MAXALIGN boundary here! */ -}; - -/* - * Only the "context" field should be accessed outside this module. + * Only the "hdrmask" field should be accessed outside this module. * We keep the rest of an allocated chunk's header marked NOACCESS when using * valgrind. But note that freed chunk headers are kept accessible, for * simplicity. */ -#define GENERATIONCHUNK_PRIVATE_LEN offsetof(GenerationChunk, context) - +#define GENERATIONCHUNK_PRIVATE_LEN offsetof(MemoryChunk, hdrmask) /* * GenerationIsValid * True iff set is valid allocation set. */ #define GenerationIsValid(set) PointerIsValid(set) -#define GenerationPointerGetChunk(ptr) \ - ((GenerationChunk *)(((char *)(ptr)) - Generation_CHUNKHDRSZ)) -#define GenerationChunkGetPointer(chk) \ - ((GenerationPointer *)(((char *)(chk)) + Generation_CHUNKHDRSZ)) +/* + * We always store external chunks on a dedicated block. This makes fetching + * the block from an external chunk easy since it's always the first and only + * chunk on the block. + */ +#define ExternalChunkGetBlock(chunk) \ + (GenerationBlock *) ((char *) chunk - Generation_BLOCKHDRSZ) /* Inlined helper functions */ -static inline void GenerationBlockInit(GenerationBlock *block, Size blksize); +static inline void GenerationBlockInit(GenerationContext *context, + GenerationBlock *block, + Size blksize); static inline bool GenerationBlockIsEmpty(GenerationBlock *block); static inline void GenerationBlockMarkEmpty(GenerationBlock *block); static inline Size GenerationBlockFreeBytes(GenerationBlock *block); static inline void GenerationBlockFree(GenerationContext *set, GenerationBlock *block); -/* - * These functions implement the MemoryContext API for Generation contexts. - */ -static void *GenerationAlloc(MemoryContext context, Size size); -static void GenerationFree(MemoryContext context, void *pointer); -static void *GenerationRealloc(MemoryContext context, void *pointer, Size size); -static void GenerationReset(MemoryContext context); -static void GenerationDelete(MemoryContext context); -static Size GenerationGetChunkSpace(MemoryContext context, void *pointer); -static bool GenerationIsEmpty(MemoryContext context); -static void GenerationStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); - -#ifdef MEMORY_CONTEXT_CHECKING -static void GenerationCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for Generation contexts. - */ -static const MemoryContextMethods GenerationMethods = { - GenerationAlloc, - GenerationFree, - GenerationRealloc, - GenerationReset, - GenerationDelete, - GenerationGetChunkSpace, - GenerationIsEmpty, - GenerationStats -#ifdef MEMORY_CONTEXT_CHECKING - ,GenerationCheck -#endif -}; - /* * Public routines @@ -223,17 +157,20 @@ GenerationContextCreate(MemoryContext parent, GenerationContext *set; GenerationBlock *block; - /* Assert we padded GenerationChunk properly */ + /* ensure MemoryChunk's size is properly maxaligned */ StaticAssertStmt(Generation_CHUNKHDRSZ == MAXALIGN(Generation_CHUNKHDRSZ), - "sizeof(GenerationChunk) is not maxaligned"); - StaticAssertStmt(offsetof(GenerationChunk, context) + sizeof(MemoryContext) == - Generation_CHUNKHDRSZ, - "padding calculation in GenerationChunk is wrong"); + "sizeof(MemoryChunk) is not maxaligned"); /* * First, validate allocation parameters. Asserts seem sufficient because * nobody varies their parameters at runtime. We somewhat arbitrarily - * enforce a minimum 1K block size. + * enforce a minimum 1K block size. We restrict the maximum block size to + * MEMORYCHUNK_MAX_BLOCKOFFSET as MemoryChunks are limited to this in + * regards to addressing the offset between the chunk and the block that + * the chunk is stored on. We would be unable to store the offset between + * the chunk and block for any chunks that were beyond + * MEMORYCHUNK_MAX_BLOCKOFFSET bytes into the block if the block was to be + * larger than this. */ Assert(initBlockSize == MAXALIGN(initBlockSize) && initBlockSize >= 1024); @@ -244,6 +181,7 @@ GenerationContextCreate(MemoryContext parent, (minContextSize == MAXALIGN(minContextSize) && minContextSize >= 1024 && minContextSize <= maxBlockSize)); + Assert(maxBlockSize <= MEMORYCHUNK_MAX_BLOCKOFFSET); /* Determine size of initial block */ allocSize = MAXALIGN(sizeof(GenerationContext)) + @@ -278,7 +216,7 @@ GenerationContextCreate(MemoryContext parent, block = (GenerationBlock *) (((char *) set) + MAXALIGN(sizeof(GenerationContext))); /* determine the block size and initialize it */ firstBlockSize = allocSize - MAXALIGN(sizeof(GenerationContext)); - GenerationBlockInit(block, firstBlockSize); + GenerationBlockInit(set, block, firstBlockSize); /* add it to the doubly-linked list of blocks */ dlist_push_head(&set->blocks, &block->node); @@ -300,9 +238,14 @@ GenerationContextCreate(MemoryContext parent, /* * Compute the allocation chunk size limit for this context. * - * Follows similar ideas as AllocSet, see aset.c for details ... + * Limit the maximum size a non-dedicated chunk can be so that we can fit + * at least Generation_CHUNK_FRACTION of chunks this big onto the maximum + * sized block. We must further limit this value so that it's no more + * than MEMORYCHUNK_MAX_VALUE. We're unable to have non-dedicated chunks + * larger than that value as we store the chunk size in the MemoryChunk + * 'value' field in the call to MemoryChunkSetHdrMask(). */ - set->allocChunkLimit = maxBlockSize; + set->allocChunkLimit = Min(maxBlockSize, MEMORYCHUNK_MAX_VALUE); while ((Size) (set->allocChunkLimit + Generation_CHUNKHDRSZ) > (Size) ((Size) (maxBlockSize - Generation_BLOCKHDRSZ) / Generation_CHUNK_FRACTION)) set->allocChunkLimit >>= 1; @@ -310,7 +253,7 @@ GenerationContextCreate(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) set, T_GenerationContext, - &GenerationMethods, + MCTX_GENERATION_ID, parent, name); @@ -326,7 +269,7 @@ GenerationContextCreate(MemoryContext parent, * The code simply frees all the blocks in the context - we don't keep any * keeper blocks or anything like that. */ -static void +void GenerationReset(MemoryContext context) { GenerationContext *set = (GenerationContext *) context; @@ -371,7 +314,7 @@ GenerationReset(MemoryContext context) * GenerationDelete * Free all memory which is allocated in the given context. */ -static void +void GenerationDelete(MemoryContext context) { /* Reset to release all releasable GenerationBlocks */ @@ -393,12 +336,12 @@ GenerationDelete(MemoryContext context) * is marked, as mcxt.c will set it to UNDEFINED. In some paths we will * return space that is marked NOACCESS - GenerationRealloc has to beware! */ -static void * +void * GenerationAlloc(MemoryContext context, Size size) { GenerationContext *set = (GenerationContext *) context; GenerationBlock *block; - GenerationChunk *chunk; + MemoryChunk *chunk; Size chunk_size = MAXALIGN(size); Size required_size = chunk_size + Generation_CHUNKHDRSZ; @@ -414,6 +357,7 @@ GenerationAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; /* block with a single (used) chunk */ + block->context = set; block->blksize = blksize; block->nchunks = 1; block->nfree = 0; @@ -421,33 +365,33 @@ GenerationAlloc(MemoryContext context, Size size) /* the block is completely full */ block->freeptr = block->endptr = ((char *) block) + blksize; - chunk = (GenerationChunk *) (((char *) block) + Generation_BLOCKHDRSZ); - chunk->block = block; - chunk->context = set; - chunk->size = chunk_size; + chunk = (MemoryChunk *) (((char *) block) + Generation_BLOCKHDRSZ); + + /* mark the MemoryChunk as externally managed */ + MemoryChunkSetHdrMaskExternal(chunk, MCTX_GENERATION_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk_size) - set_sentinel(GenerationChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) GenerationChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* add the block to the list of allocated blocks */ dlist_push_head(&set->blocks, &block->node); /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) GenerationChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return GenerationChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -516,7 +460,7 @@ GenerationAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; /* initialize the new block */ - GenerationBlockInit(block, blksize); + GenerationBlockInit(set, block, blksize); /* add it to the doubly-linked list of blocks */ dlist_push_head(&set->blocks, &block->node); @@ -533,7 +477,7 @@ GenerationAlloc(MemoryContext context, Size size) Assert(block != NULL); Assert((block->endptr - block->freeptr) >= Generation_CHUNKHDRSZ + chunk_size); - chunk = (GenerationChunk *) block->freeptr; + chunk = (MemoryChunk *) block->freeptr; /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, Generation_CHUNKHDRSZ); @@ -543,29 +487,26 @@ GenerationAlloc(MemoryContext context, Size size) Assert(block->freeptr <= block->endptr); - chunk->block = block; - chunk->context = set; - chunk->size = chunk_size; - + MemoryChunkSetHdrMask(chunk, block, chunk_size, MCTX_GENERATION_ID); #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk->size) - set_sentinel(GenerationChunkGetPointer(chunk), size); + if (size < chunk_size) + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) GenerationChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif /* Ensure any padding bytes are marked NOACCESS. */ - VALGRIND_MAKE_MEM_NOACCESS((char *) GenerationChunkGetPointer(chunk) + size, + VALGRIND_MAKE_MEM_NOACCESS((char *) MemoryChunkGetPointer(chunk) + size, chunk_size - size); /* Disallow external access to private part of chunk header. */ VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return GenerationChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* @@ -574,8 +515,10 @@ GenerationAlloc(MemoryContext context, Size size) * mem_allocated field. */ static inline void -GenerationBlockInit(GenerationBlock *block, Size blksize) +GenerationBlockInit(GenerationContext *context, GenerationBlock *block, + Size blksize) { + block->context = context; block->blksize = blksize; block->nchunks = 0; block->nfree = 0; @@ -661,36 +604,49 @@ GenerationBlockFree(GenerationContext *set, GenerationBlock *block) * Update number of chunks in the block, and if all chunks in the block * are now free then discard the block. */ -static void -GenerationFree(MemoryContext context, void *pointer) +void +GenerationFree(void *pointer) { - GenerationContext *set = (GenerationContext *) context; - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); GenerationBlock *block; + GenerationContext *set; +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + Size chunksize; +#endif + + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + chunksize = block->endptr - (char *) pointer; +#endif + } + else + { + block = MemoryChunkGetBlock(chunk); +#if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) + chunksize = MemoryChunkGetValue(chunk); +#endif + } /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - block = chunk->block; - #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunk->size) + if (chunk->requested_size < chunksize) if (!sentinel_ok(pointer, chunk->requested_size)) elog(WARNING, "detected write past chunk end in %s %p", - ((MemoryContext) set)->name, chunk); + ((MemoryContext) block->context)->name, chunk); #endif #ifdef CLOBBER_FREED_MEMORY - wipe_mem(pointer, chunk->size); + wipe_mem(pointer, chunksize); #endif - /* Reset context to NULL in freed chunks */ - chunk->context = NULL; - #ifdef MEMORY_CONTEXT_CHECKING - /* Reset requested_size to 0 in freed chunks */ - chunk->requested_size = 0; + /* Reset requested_size to InvalidAllocSize in freed chunks */ + chunk->requested_size = InvalidAllocSize; #endif block->nfree += 1; @@ -702,6 +658,8 @@ GenerationFree(MemoryContext context, void *pointer) if (block->nfree < block->nchunks) return; + set = block->context; + /* Don't try to free the keeper block, just mark it empty */ if (block == set->keeper) { @@ -732,7 +690,7 @@ GenerationFree(MemoryContext context, void *pointer) */ dlist_delete(&block->node); - context->mem_allocated -= block->blksize; + set->header.mem_allocated -= block->blksize; free(block); } @@ -742,18 +700,30 @@ GenerationFree(MemoryContext context, void *pointer) * and discard the old one. The only exception is when the new size fits * into the old chunk - in that case we just update chunk header. */ -static void * -GenerationRealloc(MemoryContext context, void *pointer, Size size) +void * +GenerationRealloc(void *pointer, Size size) { - GenerationContext *set = (GenerationContext *) context; - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationContext *set; + GenerationBlock *block; GenerationPointer newPointer; Size oldsize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - oldsize = chunk->size; + if (MemoryChunkIsExternal(chunk)) + { + block = ExternalChunkGetBlock(chunk); + oldsize = block->endptr - (char *) pointer; + } + else + { + block = MemoryChunkGetBlock(chunk); + oldsize = MemoryChunkGetValue(chunk); + } + + set = block->context; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ @@ -848,7 +818,7 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) memcpy(newPointer, pointer, oldsize); /* free old chunk */ - GenerationFree((MemoryContext) set, pointer); + GenerationFree(pointer); return newPointer; } @@ -858,23 +828,48 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -GenerationGetChunkSpace(MemoryContext context, void *pointer) +MemoryContext +GenerationGetChunkContext(void *pointer) { - GenerationChunk *chunk = GenerationPointerGetChunk(pointer); - Size result; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationBlock *block; - VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - result = chunk->size + Generation_CHUNKHDRSZ; - VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return result; + if (MemoryChunkIsExternal(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (GenerationBlock *) MemoryChunkGetBlock(chunk); + + return &block->context->header; +} + +/* + * GenerationGetChunkSpace + * Given a currently-allocated chunk, determine the total space + * it occupies (including all memory-allocation overhead). + */ +Size +GenerationGetChunkSpace(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + Size chunksize; + + if (MemoryChunkIsExternal(chunk)) + { + GenerationBlock *block = ExternalChunkGetBlock(chunk); + + chunksize = block->endptr - (char *) pointer; + } + else + chunksize = MemoryChunkGetValue(chunk); + + return Generation_CHUNKHDRSZ + chunksize; } /* * GenerationIsEmpty * Is a GenerationContext empty of any allocated space? */ -static bool +bool GenerationIsEmpty(MemoryContext context) { GenerationContext *set = (GenerationContext *) context; @@ -903,7 +898,7 @@ GenerationIsEmpty(MemoryContext context) * XXX freespace only accounts for empty space at the end of the block, not * space of freed chunks (which is unknown). */ -static void +void GenerationStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr) @@ -961,7 +956,7 @@ GenerationStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void GenerationCheck(MemoryContext context) { GenerationContext *gen = (GenerationContext *) context; @@ -976,6 +971,7 @@ GenerationCheck(MemoryContext context) int nfree, nchunks; char *ptr; + bool has_external_chunk = false; total_allocated += block->blksize; @@ -987,6 +983,11 @@ GenerationCheck(MemoryContext context) elog(WARNING, "problem in Generation %s: number of free chunks %d in block %p exceeds %d allocated", name, block->nfree, block, block->nchunks); + /* check block belongs to the correct context */ + if (block->context != gen) + elog(WARNING, "problem in Generation %s: bogus context link in block %p", + name, block); + /* Now walk through the chunks and count them. */ nfree = 0; nchunks = 0; @@ -994,42 +995,47 @@ GenerationCheck(MemoryContext context) while (ptr < block->freeptr) { - GenerationChunk *chunk = (GenerationChunk *) ptr; + MemoryChunk *chunk = (MemoryChunk *) ptr; + GenerationBlock *chunkblock; + Size chunksize; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); + if (MemoryChunkIsExternal(chunk)) + { + chunkblock = ExternalChunkGetBlock(chunk); + chunksize = block->endptr - (char *) MemoryChunkGetPointer(chunk); + has_external_chunk = true; + } + else + { + chunkblock = MemoryChunkGetBlock(chunk); + chunksize = MemoryChunkGetValue(chunk); + } + /* move to the next chunk */ - ptr += (chunk->size + Generation_CHUNKHDRSZ); + ptr += (chunksize + Generation_CHUNKHDRSZ); nchunks += 1; /* chunks have both block and context pointers, so check both */ - if (chunk->block != block) + if (chunkblock != block) elog(WARNING, "problem in Generation %s: bogus block link in block %p, chunk %p", name, block, chunk); - /* - * Check for valid context pointer. Note this is an incomplete - * test, since palloc(0) produces an allocated chunk with - * requested_size == 0. - */ - if ((chunk->requested_size > 0 && chunk->context != gen) || - (chunk->context != gen && chunk->context != NULL)) - elog(WARNING, "problem in Generation %s: bogus context link in block %p, chunk %p", - name, block, chunk); - - /* now make sure the chunk size is correct */ - if (chunk->size < chunk->requested_size || - chunk->size != MAXALIGN(chunk->size)) - elog(WARNING, "problem in Generation %s: bogus chunk size in block %p, chunk %p", - name, block, chunk); /* is chunk allocated? */ - if (chunk->context != NULL) + if (chunk->requested_size != InvalidAllocSize) { - /* check sentinel, but only in allocated blocks */ - if (chunk->requested_size < chunk->size && + /* now make sure the chunk size is correct */ + if (chunksize < chunk->requested_size || + chunksize != MAXALIGN(chunksize)) + elog(WARNING, "problem in Generation %s: bogus chunk size in block %p, chunk %p", + name, block, chunk); + + /* check sentinel */ + if (chunk->requested_size < chunksize && !sentinel_ok(chunk, Generation_CHUNKHDRSZ + chunk->requested_size)) elog(WARNING, "problem in Generation %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); @@ -1041,7 +1047,7 @@ GenerationCheck(MemoryContext context) * If chunk is allocated, disallow external access to private part * of chunk header. */ - if (chunk->context != NULL) + if (chunk->requested_size != InvalidAllocSize) VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); } @@ -1056,6 +1062,11 @@ GenerationCheck(MemoryContext context) if (nfree != block->nfree) elog(WARNING, "problem in Generation %s: number of free chunks %d in block %p does not match header %d", name, nfree, block, block->nfree); + + if (has_external_chunk && nchunks > 1) + elog(WARNING, "problem in Generation %s: external chunk on non-dedicated block %p", + name, block); + } Assert(total_allocated == context->mem_allocated); diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index e12be1b9bd..7c53222b9d 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -29,12 +29,57 @@ #include "utils/fmgrprotos.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_internal.h" /***************************************************************************** * GLOBAL MEMORY * *****************************************************************************/ +static const MemoryContextMethods mcxt_methods[] = { + /* aset.c */ + [MCTX_ASET_ID].alloc = AllocSetAlloc, + [MCTX_ASET_ID].free_p = AllocSetFree, + [MCTX_ASET_ID].realloc = AllocSetRealloc, + [MCTX_ASET_ID].reset = AllocSetReset, + [MCTX_ASET_ID].delete_context = AllocSetDelete, + [MCTX_ASET_ID].get_chunk_context = AllocSetGetChunkContext, + [MCTX_ASET_ID].get_chunk_space = AllocSetGetChunkSpace, + [MCTX_ASET_ID].is_empty = AllocSetIsEmpty, + [MCTX_ASET_ID].stats = AllocSetStats, +#ifdef MEMORY_CONTEXT_CHECKING + [MCTX_ASET_ID].check = AllocSetCheck, +#endif + + /* generation.c */ + [MCTX_GENERATION_ID].alloc = GenerationAlloc, + [MCTX_GENERATION_ID].free_p = GenerationFree, + [MCTX_GENERATION_ID].realloc = GenerationRealloc, + [MCTX_GENERATION_ID].reset = GenerationReset, + [MCTX_GENERATION_ID].delete_context = GenerationDelete, + [MCTX_GENERATION_ID].get_chunk_context = GenerationGetChunkContext, + [MCTX_GENERATION_ID].get_chunk_space = GenerationGetChunkSpace, + [MCTX_GENERATION_ID].is_empty = GenerationIsEmpty, + [MCTX_GENERATION_ID].stats = GenerationStats, +#ifdef MEMORY_CONTEXT_CHECKING + [MCTX_GENERATION_ID].check = GenerationCheck, +#endif + + /* slab.c */ + [MCTX_SLAB_ID].alloc = SlabAlloc, + [MCTX_SLAB_ID].free_p = SlabFree, + [MCTX_SLAB_ID].realloc = SlabRealloc, + [MCTX_SLAB_ID].reset = SlabReset, + [MCTX_SLAB_ID].delete_context = SlabDelete, + [MCTX_SLAB_ID].get_chunk_context = SlabGetChunkContext, + [MCTX_SLAB_ID].get_chunk_space = SlabGetChunkSpace, + [MCTX_SLAB_ID].is_empty = SlabIsEmpty, + [MCTX_SLAB_ID].stats = SlabStats +#ifdef MEMORY_CONTEXT_CHECKING + ,[MCTX_SLAB_ID].check = SlabCheck +#endif +}; + /* * CurrentMemoryContext * Default memory context for allocations. @@ -73,6 +118,13 @@ static void MemoryContextStatsPrint(MemoryContext context, void *passthru, #define AssertNotInCriticalSection(context) \ Assert(CritSectionCount == 0 || (context)->allowInCritSection) +/* + * Call the given function in the MemoryContextMethods for the memory context + * type that 'pointer' belongs to. + */ +#define MCXT_METHOD(pointer, method) \ + mcxt_methods[GetMemoryChunkMethodID(pointer)].method + /***************************************************************************** * EXPORTED ROUTINES * @@ -422,6 +474,17 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) context->allowInCritSection = allow; } +/* + * GetMemoryChunkContext + * Given a currently-allocated chunk, determine the MemoryContext that + * the chunk belongs to. + */ +MemoryContext +GetMemoryChunkContext(void *pointer) +{ + return MCXT_METHOD(pointer, get_chunk_context) (pointer); +} + /* * GetMemoryChunkSpace * Given a currently-allocated chunk, determine the total space @@ -433,9 +496,7 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) Size GetMemoryChunkSpace(void *pointer) { - MemoryContext context = GetMemoryChunkContext(pointer); - - return context->methods->get_chunk_space(context, pointer); + return MCXT_METHOD(pointer, get_chunk_space) (pointer); } /* @@ -814,7 +875,7 @@ MemoryContextContains(MemoryContext context, void *pointer) void MemoryContextCreate(MemoryContext node, NodeTag tag, - const MemoryContextMethods *methods, + MemoryContextMethodID method_id, MemoryContext parent, const char *name) { @@ -824,7 +885,7 @@ MemoryContextCreate(MemoryContext node, /* Initialize all standard fields of memory context header */ node->type = tag; node->isReset = true; - node->methods = methods; + node->methods = &mcxt_methods[method_id]; node->parent = parent; node->firstchild = NULL; node->mem_allocated = 0; @@ -1174,9 +1235,11 @@ palloc_extended(Size size, int flags) void pfree(void *pointer) { +#ifdef USE_VALGRIND MemoryContext context = GetMemoryChunkContext(pointer); +#endif - context->methods->free_p(context, pointer); + MCXT_METHOD(pointer, free_p) (pointer); VALGRIND_MEMPOOL_FREE(context, pointer); } @@ -1187,7 +1250,9 @@ pfree(void *pointer) void * repalloc(void *pointer, Size size) { +#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND) MemoryContext context = GetMemoryChunkContext(pointer); +#endif void *ret; if (!AllocSizeIsValid(size)) @@ -1198,15 +1263,17 @@ repalloc(void *pointer, Size size) /* isReset must be false already */ Assert(!context->isReset); - ret = context->methods->realloc(context, pointer, size); + ret = MCXT_METHOD(pointer, realloc) (pointer, size); if (unlikely(ret == NULL)) { + MemoryContext cxt = GetMemoryChunkContext(pointer); + MemoryContextStats(TopMemoryContext); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"), errdetail("Failed on request of size %zu in memory context \"%s\".", - size, context->name))); + size, cxt->name))); } VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size); @@ -1257,7 +1324,9 @@ MemoryContextAllocHuge(MemoryContext context, Size size) void * repalloc_huge(void *pointer, Size size) { +#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND) MemoryContext context = GetMemoryChunkContext(pointer); +#endif void *ret; if (!AllocHugeSizeIsValid(size)) @@ -1268,15 +1337,17 @@ repalloc_huge(void *pointer, Size size) /* isReset must be false already */ Assert(!context->isReset); - ret = context->methods->realloc(context, pointer, size); + ret = MCXT_METHOD(pointer, realloc) (pointer, size); if (unlikely(ret == NULL)) { + MemoryContext cxt = GetMemoryChunkContext(pointer); + MemoryContextStats(TopMemoryContext); ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"), errdetail("Failed on request of size %zu in memory context \"%s\".", - size, context->name))); + size, cxt->name))); } VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size); diff --git a/src/backend/utils/mmgr/slab.c b/src/backend/utils/mmgr/slab.c index 67d97b22e5..e042e596f7 100644 --- a/src/backend/utils/mmgr/slab.c +++ b/src/backend/utils/mmgr/slab.c @@ -55,6 +55,8 @@ #include "lib/ilist.h" #include "utils/memdebug.h" #include "utils/memutils.h" +#include "utils/memutils_memorychunk.h" +#include "utils/memutils_internal.h" /* * SlabContext is a specialized implementation of MemoryContext. @@ -90,75 +92,23 @@ typedef struct SlabBlock dlist_node node; /* doubly-linked list */ int nfree; /* number of free chunks */ int firstFreeChunk; /* index of the first free chunk in the block */ -} SlabBlock; - -/* - * SlabChunk - * The prefix of each piece of memory in a SlabBlock - * - * Note: to meet the memory context APIs, the payload area of the chunk must - * be maxaligned, and the "slab" link must be immediately adjacent to the - * payload area (cf. GetMemoryChunkContext). Since we support no machines on - * which MAXALIGN is more than twice sizeof(void *), this happens without any - * special hacking in this struct declaration. But there is a static - * assertion below that the alignment is done correctly. - */ -typedef struct SlabChunk -{ - SlabBlock *block; /* block owning this chunk */ SlabContext *slab; /* owning context */ - /* there must not be any padding to reach a MAXALIGN boundary here! */ -} SlabChunk; +} SlabBlock; +#define Slab_CHUNKHDRSZ sizeof(MemoryChunk) #define SlabPointerGetChunk(ptr) \ - ((SlabChunk *)(((char *)(ptr)) - sizeof(SlabChunk))) + ((MemoryChunk *)(((char *)(ptr)) - sizeof(MemoryChunk))) #define SlabChunkGetPointer(chk) \ - ((void *)(((char *)(chk)) + sizeof(SlabChunk))) + ((void *)(((char *)(chk)) + sizeof(MemoryChunk))) #define SlabBlockGetChunk(slab, block, idx) \ - ((SlabChunk *) ((char *) (block) + sizeof(SlabBlock) \ + ((MemoryChunk *) ((char *) (block) + sizeof(SlabBlock) \ + (idx * slab->fullChunkSize))) #define SlabBlockStart(block) \ ((char *) block + sizeof(SlabBlock)) #define SlabChunkIndex(slab, block, chunk) \ (((char *) chunk - SlabBlockStart(block)) / slab->fullChunkSize) -/* - * These functions implement the MemoryContext API for Slab contexts. - */ -static void *SlabAlloc(MemoryContext context, Size size); -static void SlabFree(MemoryContext context, void *pointer); -static void *SlabRealloc(MemoryContext context, void *pointer, Size size); -static void SlabReset(MemoryContext context); -static void SlabDelete(MemoryContext context); -static Size SlabGetChunkSpace(MemoryContext context, void *pointer); -static bool SlabIsEmpty(MemoryContext context); -static void SlabStats(MemoryContext context, - MemoryStatsPrintFunc printfunc, void *passthru, - MemoryContextCounters *totals, - bool print_to_stderr); -#ifdef MEMORY_CONTEXT_CHECKING -static void SlabCheck(MemoryContext context); -#endif - -/* - * This is the virtual function table for Slab contexts. - */ -static const MemoryContextMethods SlabMethods = { - SlabAlloc, - SlabFree, - SlabRealloc, - SlabReset, - SlabDelete, - SlabGetChunkSpace, - SlabIsEmpty, - SlabStats -#ifdef MEMORY_CONTEXT_CHECKING - ,SlabCheck -#endif -}; - - /* * SlabContextCreate * Create a new Slab context. @@ -168,8 +118,7 @@ static const MemoryContextMethods SlabMethods = { * blockSize: allocation block size * chunkSize: allocation chunk size * - * The chunkSize may not exceed: - * MAXALIGN_DOWN(SIZE_MAX) - MAXALIGN(sizeof(SlabBlock)) - sizeof(SlabChunk) + * The MAXALIGN(chunkSize) may not exceed MEMORYCHUNK_MAX_VALUE */ MemoryContext SlabContextCreate(MemoryContext parent, @@ -184,19 +133,14 @@ SlabContextCreate(MemoryContext parent, SlabContext *slab; int i; - /* Assert we padded SlabChunk properly */ - StaticAssertStmt(sizeof(SlabChunk) == MAXALIGN(sizeof(SlabChunk)), - "sizeof(SlabChunk) is not maxaligned"); - StaticAssertStmt(offsetof(SlabChunk, slab) + sizeof(MemoryContext) == - sizeof(SlabChunk), - "padding calculation in SlabChunk is wrong"); + Assert(MAXALIGN(chunkSize) <= MEMORYCHUNK_MAX_VALUE); /* Make sure the linked list node fits inside a freed chunk */ if (chunkSize < sizeof(int)) chunkSize = sizeof(int); /* chunk, including SLAB header (both addresses nicely aligned) */ - fullChunkSize = sizeof(SlabChunk) + MAXALIGN(chunkSize); + fullChunkSize = Slab_CHUNKHDRSZ + MAXALIGN(chunkSize); /* Make sure the block can store at least one chunk. */ if (blockSize < fullChunkSize + sizeof(SlabBlock)) @@ -265,7 +209,7 @@ SlabContextCreate(MemoryContext parent, /* Finally, do the type-independent part of context creation */ MemoryContextCreate((MemoryContext) slab, T_SlabContext, - &SlabMethods, + MCTX_SLAB_ID, parent, name); @@ -279,7 +223,7 @@ SlabContextCreate(MemoryContext parent, * The code simply frees all the blocks in the context - we don't keep any * keeper blocks or anything like that. */ -static void +void SlabReset(MemoryContext context) { int i; @@ -322,7 +266,7 @@ SlabReset(MemoryContext context) * SlabDelete * Free all memory which is allocated in the given context. */ -static void +void SlabDelete(MemoryContext context) { /* Reset to release all the SlabBlocks */ @@ -336,12 +280,12 @@ SlabDelete(MemoryContext context) * Returns pointer to allocated memory of given size or NULL if * request could not be completed; memory is added to the slab. */ -static void * +void * SlabAlloc(MemoryContext context, Size size) { SlabContext *slab = castNode(SlabContext, context); SlabBlock *block; - SlabChunk *chunk; + MemoryChunk *chunk; int idx; Assert(slab); @@ -370,6 +314,7 @@ SlabAlloc(MemoryContext context, Size size) block->nfree = slab->chunksPerBlock; block->firstFreeChunk = 0; + block->slab = slab; /* * Put all the chunks on a freelist. Walk the chunks and point each @@ -378,7 +323,7 @@ SlabAlloc(MemoryContext context, Size size) for (idx = 0; idx < slab->chunksPerBlock; idx++) { chunk = SlabBlockGetChunk(slab, block, idx); - *(int32 *) SlabChunkGetPointer(chunk) = (idx + 1); + *(int32 *) MemoryChunkGetPointer(chunk) = (idx + 1); } /* @@ -426,8 +371,8 @@ SlabAlloc(MemoryContext context, Size size) * Remove the chunk from the freelist head. The index of the next free * chunk is stored in the chunk itself. */ - VALGRIND_MAKE_MEM_DEFINED(SlabChunkGetPointer(chunk), sizeof(int32)); - block->firstFreeChunk = *(int32 *) SlabChunkGetPointer(chunk); + VALGRIND_MAKE_MEM_DEFINED(MemoryChunkGetPointer(chunk), sizeof(int32)); + block->firstFreeChunk = *(int32 *) MemoryChunkGetPointer(chunk); Assert(block->firstFreeChunk >= 0); Assert(block->firstFreeChunk <= slab->chunksPerBlock); @@ -464,47 +409,47 @@ SlabAlloc(MemoryContext context, Size size) slab->minFreeChunks = 0; /* Prepare to initialize the chunk header. */ - VALGRIND_MAKE_MEM_UNDEFINED(chunk, sizeof(SlabChunk)); - - chunk->block = block; - chunk->slab = slab; + VALGRIND_MAKE_MEM_UNDEFINED(chunk, Slab_CHUNKHDRSZ); + MemoryChunkSetHdrMask(chunk, block, MAXALIGN(slab->chunkSize), + MCTX_SLAB_ID); #ifdef MEMORY_CONTEXT_CHECKING /* slab mark to catch clobber of "unused" space */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) { - set_sentinel(SlabChunkGetPointer(chunk), size); + set_sentinel(MemoryChunkGetPointer(chunk), size); VALGRIND_MAKE_MEM_NOACCESS(((char *) chunk) + - sizeof(SlabChunk) + slab->chunkSize, + Slab_CHUNKHDRSZ + slab->chunkSize, slab->fullChunkSize - - (slab->chunkSize + sizeof(SlabChunk))); + (slab->chunkSize + Slab_CHUNKHDRSZ)); } #endif + #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ - randomize_mem((char *) SlabChunkGetPointer(chunk), size); + randomize_mem((char *) MemoryChunkGetPointer(chunk), size); #endif Assert(slab->nblocks * slab->blockSize == context->mem_allocated); - return SlabChunkGetPointer(chunk); + return MemoryChunkGetPointer(chunk); } /* * SlabFree * Frees allocated memory; memory is removed from the slab. */ -static void -SlabFree(MemoryContext context, void *pointer) +void +SlabFree(void *pointer) { int idx; - SlabContext *slab = castNode(SlabContext, context); - SlabChunk *chunk = SlabPointerGetChunk(pointer); - SlabBlock *block = chunk->block; + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) if (!sentinel_ok(pointer, slab->chunkSize)) elog(WARNING, "detected write past chunk end in %s %p", slab->header.name, chunk); @@ -560,13 +505,13 @@ SlabFree(MemoryContext context, void *pointer) { free(block); slab->nblocks--; - context->mem_allocated -= slab->blockSize; + slab->header.mem_allocated -= slab->blockSize; } else dlist_push_head(&slab->freelist[block->nfree], &block->node); Assert(slab->nblocks >= 0); - Assert(slab->nblocks * slab->blockSize == context->mem_allocated); + Assert(slab->nblocks * slab->blockSize == slab->header.mem_allocated); } /* @@ -582,13 +527,14 @@ SlabFree(MemoryContext context, void *pointer) * rather pointless - Slab is meant for chunks of constant size, and moreover * realloc is usually used to enlarge the chunk. */ -static void * -SlabRealloc(MemoryContext context, void *pointer, Size size) +void * +SlabRealloc(void *pointer, Size size) { - SlabContext *slab = castNode(SlabContext, context); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; Assert(slab); - /* can't do actual realloc with slab, but let's try to be gentle */ if (size == slab->chunkSize) return pointer; @@ -597,15 +543,33 @@ SlabRealloc(MemoryContext context, void *pointer, Size size) return NULL; /* keep compiler quiet */ } +/* + * SlabGetChunkContext + * Return the MemoryContext that 'pointer' belongs to. + */ +MemoryContext +SlabGetChunkContext(void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; + + Assert(slab != NULL); + + return &slab->header; +} + /* * SlabGetChunkSpace * Given a currently-allocated chunk, determine the total space * it occupies (including all memory-allocation overhead). */ -static Size -SlabGetChunkSpace(MemoryContext context, void *pointer) +Size +SlabGetChunkSpace(void *pointer) { - SlabContext *slab = castNode(SlabContext, context); + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block = MemoryChunkGetBlock(chunk); + SlabContext *slab = block->slab; Assert(slab); @@ -616,7 +580,7 @@ SlabGetChunkSpace(MemoryContext context, void *pointer) * SlabIsEmpty * Is an Slab empty of any allocated space? */ -static bool +bool SlabIsEmpty(MemoryContext context) { SlabContext *slab = castNode(SlabContext, context); @@ -635,7 +599,7 @@ SlabIsEmpty(MemoryContext context) * totals: if not NULL, add stats about this context into *totals. * print_to_stderr: print stats to stderr if true, elog otherwise. */ -static void +void SlabStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, @@ -697,7 +661,7 @@ SlabStats(MemoryContext context, * find yourself in an infinite loop when trouble occurs, because this * routine will be entered again when elog cleanup tries to release memory! */ -static void +void SlabCheck(MemoryContext context) { int i; @@ -728,6 +692,11 @@ SlabCheck(MemoryContext context) elog(WARNING, "problem in slab %s: number of free chunks %d in block %p does not match freelist %d", name, block->nfree, block, i); + /* make sure the slab pointer correctly points to this context */ + if (block->slab != slab) + elog(WARNING, "problem in slab %s: bogus slab link in block %p", + name, block); + /* reset the bitmap of free chunks for this block */ memset(slab->freechunks, 0, (slab->chunksPerBlock * sizeof(bool))); idx = block->firstFreeChunk; @@ -742,7 +711,7 @@ SlabCheck(MemoryContext context) nfree = 0; while (idx < slab->chunksPerBlock) { - SlabChunk *chunk; + MemoryChunk *chunk; /* count the chunk as free, add it to the bitmap */ nfree++; @@ -750,8 +719,8 @@ SlabCheck(MemoryContext context) /* read index of the next free chunk */ chunk = SlabBlockGetChunk(slab, block, idx); - VALGRIND_MAKE_MEM_DEFINED(SlabChunkGetPointer(chunk), sizeof(int32)); - idx = *(int32 *) SlabChunkGetPointer(chunk); + VALGRIND_MAKE_MEM_DEFINED(MemoryChunkGetPointer(chunk), sizeof(int32)); + idx = *(int32 *) MemoryChunkGetPointer(chunk); } for (j = 0; j < slab->chunksPerBlock; j++) @@ -759,19 +728,19 @@ SlabCheck(MemoryContext context) /* non-zero bit in the bitmap means chunk the chunk is used */ if (!slab->freechunks[j]) { - SlabChunk *chunk = SlabBlockGetChunk(slab, block, j); - - /* chunks have both block and slab pointers, so check both */ - if (chunk->block != block) + MemoryChunk *chunk = SlabBlockGetChunk(slab, block, j); + SlabBlock *chunkblock = (SlabBlock *) MemoryChunkGetBlock(chunk); + + /* + * check the chunk's blockoffset correctly points back to + * the block + */ + if (chunkblock != block) elog(WARNING, "problem in slab %s: bogus block link in block %p, chunk %p", name, block, chunk); - if (chunk->slab != slab) - elog(WARNING, "problem in slab %s: bogus slab link in block %p, chunk %p", - name, block, chunk); - /* there might be sentinel (thanks to alignment) */ - if (slab->chunkSize < (slab->fullChunkSize - sizeof(SlabChunk))) + if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) if (!sentinel_ok(chunk, slab->chunkSize)) elog(WARNING, "problem in slab %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); diff --git a/src/include/nodes/memnodes.h b/src/include/nodes/memnodes.h index 16cd56da6d..63d07358cd 100644 --- a/src/include/nodes/memnodes.h +++ b/src/include/nodes/memnodes.h @@ -59,11 +59,12 @@ typedef struct MemoryContextMethods { void *(*alloc) (MemoryContext context, Size size); /* call this free_p in case someone #define's free() */ - void (*free_p) (MemoryContext context, void *pointer); - void *(*realloc) (MemoryContext context, void *pointer, Size size); + void (*free_p) (void *pointer); + void *(*realloc) (void *pointer, Size size); void (*reset) (MemoryContext context); void (*delete_context) (MemoryContext context); - Size (*get_chunk_space) (MemoryContext context, void *pointer); + MemoryContext (*get_chunk_context) (void *pointer); + Size (*get_chunk_space) (void *pointer); bool (*is_empty) (MemoryContext context); void (*stats) (MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, diff --git a/src/include/utils/memutils.h b/src/include/utils/memutils.h index 495d1af201..52bc41ec53 100644 --- a/src/include/utils/memutils.h +++ b/src/include/utils/memutils.h @@ -41,8 +41,11 @@ #define AllocSizeIsValid(size) ((Size) (size) <= MaxAllocSize) +/* Must be less than SIZE_MAX */ #define MaxAllocHugeSize (SIZE_MAX / 2) +#define InvalidAllocSize SIZE_MAX + #define AllocHugeSizeIsValid(size) ((Size) (size) <= MaxAllocHugeSize) @@ -79,6 +82,7 @@ extern void MemoryContextDeleteChildren(MemoryContext context); extern void MemoryContextSetIdentifier(MemoryContext context, const char *id); extern void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent); +extern MemoryContext GetMemoryChunkContext(void *pointer); extern Size GetMemoryChunkSpace(void *pointer); extern MemoryContext MemoryContextGetParent(MemoryContext context); extern bool MemoryContextIsEmpty(MemoryContext context); @@ -98,53 +102,6 @@ extern bool MemoryContextContains(MemoryContext context, void *pointer); #define MemoryContextCopyAndSetIdentifier(cxt, id) \ MemoryContextSetIdentifier(cxt, MemoryContextStrdup(cxt, id)) -/* - * GetMemoryChunkContext - * Given a currently-allocated chunk, determine the context - * it belongs to. - * - * All chunks allocated by any memory context manager are required to be - * preceded by the corresponding MemoryContext stored, without padding, in the - * preceding sizeof(void*) bytes. A currently-allocated chunk must contain a - * backpointer to its owning context. The backpointer is used by pfree() and - * repalloc() to find the context to call. - */ -#ifndef FRONTEND -static inline MemoryContext -GetMemoryChunkContext(void *pointer) -{ - MemoryContext context; - - /* - * Try to detect bogus pointers handed to us, poorly though we can. - * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an - * allocated chunk. - */ - Assert(pointer != NULL); - Assert(pointer == (void *) MAXALIGN(pointer)); - - /* - * OK, it's probably safe to look at the context. - */ - context = *(MemoryContext *) (((char *) pointer) - sizeof(void *)); - - AssertArg(MemoryContextIsValid(context)); - - return context; -} -#endif - -/* - * This routine handles the context-type-independent part of memory - * context creation. It's intended to be called from context-type- - * specific creation routines, and noplace else. - */ -extern void MemoryContextCreate(MemoryContext node, - NodeTag tag, - const MemoryContextMethods *methods, - MemoryContext parent, - const char *name); - extern void HandleLogMemoryContextInterrupt(void); extern void ProcessLogMemoryContextInterrupt(void); diff --git a/src/include/utils/memutils_internal.h b/src/include/utils/memutils_internal.h new file mode 100644 index 0000000000..4a95a7236e --- /dev/null +++ b/src/include/utils/memutils_internal.h @@ -0,0 +1,130 @@ +/*------------------------------------------------------------------------- + * + * memutils_internal.h + * This file contains declarations for memory allocation utility + * functions for internal use. + * + * + * Portions Copyright (c) 2022, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/utils/memutils_internal.h + * + *------------------------------------------------------------------------- + */ + +#ifndef MEMUTILS_INTERNAL_H +#define MEMUTILS_INTERNAL_H + +#include "utils/memutils.h" + +extern void *AllocSetAlloc(MemoryContext context, Size size); +extern void AllocSetFree(void *pointer); +extern void *AllocSetRealloc(void *pointer, Size size); +extern void AllocSetReset(MemoryContext context); +extern void AllocSetDelete(MemoryContext context); +extern MemoryContext AllocSetGetChunkContext(void *pointer); +extern Size AllocSetGetChunkSpace(void *pointer); +extern bool AllocSetIsEmpty(MemoryContext context); +extern void AllocSetStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); + +#ifdef MEMORY_CONTEXT_CHECKING +extern void AllocSetCheck(MemoryContext context); +#endif + + +extern void *GenerationAlloc(MemoryContext context, Size size); +extern void GenerationFree(void *pointer); +extern void *GenerationRealloc(void *pointer, Size size); +extern void GenerationReset(MemoryContext context); +extern void GenerationDelete(MemoryContext context); +extern MemoryContext GenerationGetChunkContext(void *pointer); +extern Size GenerationGetChunkSpace(void *pointer); +extern bool GenerationIsEmpty(MemoryContext context); +extern void GenerationStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); + +#ifdef MEMORY_CONTEXT_CHECKING +extern void GenerationCheck(MemoryContext context); +#endif + + +/* + * These functions implement the MemoryContext API for Slab contexts. + */ +extern void *SlabAlloc(MemoryContext context, Size size); +extern void SlabFree(void *pointer); +extern void *SlabRealloc(void *pointer, Size size); +extern void SlabReset(MemoryContext context); +extern void SlabDelete(MemoryContext context); +extern MemoryContext SlabGetChunkContext(void *pointer); +extern Size SlabGetChunkSpace(void *pointer); +extern bool SlabIsEmpty(MemoryContext context); +extern void SlabStats(MemoryContext context, + MemoryStatsPrintFunc printfunc, void *passthru, + MemoryContextCounters *totals, + bool print_to_stderr); +#ifdef MEMORY_CONTEXT_CHECKING +extern void SlabCheck(MemoryContext context); +#endif + +/* + * MemoryContextMethodID + * A unique identifier for each MemoryContext implementation which + * indicates the index into the mcxt_methods[] array. See mcxt.c. + */ +typedef enum MemoryContextMethodID +{ + MCTX_ASET_ID, + MCTX_GENERATION_ID, + MCTX_SLAB_ID, +} MemoryContextMethodID; + +/* + * The number of bits that 8-byte memory chunk headers can use to encode the + * MemoryContextMethodID. + */ +#define MEMORY_CONTEXT_METHODID_BITS 3 +/* + * The maximum possible value of for a MemoryContextMethodID and the bitmask + * for binary ANDing out unrelated bits in the 8-byte chunk header. This must + * be set to the maximum value that can be represented by + * MEMORY_CONTEXT_METHODID_BITS bits. + */ +#define MEMORY_CONTEXT_METHODID_MASK UINT64CONST(7) + +/* + * This routine handles the context-type-independent part of memory + * context creation. It's intended to be called from context-type- + * specific creation routines, and noplace else. + */ +extern void MemoryContextCreate(MemoryContext node, + NodeTag tag, + MemoryContextMethodID method_id, + MemoryContext parent, + const char *name); + +static inline MemoryContextMethodID +GetMemoryChunkMethodID(void *pointer) +{ + uint64 header; + + /* + * Try to detect bogus pointers handed to us, poorly though we can. + * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an + * allocated chunk. + */ + Assert(pointer != NULL); + Assert(pointer == (void *) MAXALIGN(pointer)); + + header = *((uint64 *) ((char *) pointer - sizeof(uint64))); + + return (MemoryContextMethodID) (header & MEMORY_CONTEXT_METHODID_MASK); +} + +#endif /* MEMUTILS_INTERNAL_H */ diff --git a/src/include/utils/memutils_memorychunk.h b/src/include/utils/memutils_memorychunk.h new file mode 100644 index 0000000000..8697449a93 --- /dev/null +++ b/src/include/utils/memutils_memorychunk.h @@ -0,0 +1,231 @@ +/*------------------------------------------------------------------------- + * + * memutils_memorychunk.h + * Here we define a struct named MemoryChunk which implementations of + * MemoryContexts may use as a header for chunks of memory they allocate. + * + * A MemoryChunk provides a lightweight header which a MemoryContext can use + * to store a reference back to the block the which the given chunk is + * allocated on and also an additional 30-bits to store another value such as + * the size of the allocated chunk. + * + * Although MemoryChunks are used by each of our MemoryContexts, future + * implementations may choose to implement their own method for storing chunk + * headers. The only requirement is that the header end with an 8-byte value + * which the least significant 3-bits of are set to the MemoryContextMethodID + * of the given context. + * + * By default, a MemoryChunk is 8 bytes in size, however when + * MEMORY_CONTEXT_CHECKING is defined the header becomes 16 bytes in size due + * to the additional requested_size field. The MemoryContext may use this + * field for whatever they wish, but it is intended to be used for additional + * checks which are only done in MEMORY_CONTEXT_CHECKING builds. + * + * The MemoryChunk contains a uint64 field named 'hdrmask'. This field is + * used to encode 4 separate pieces of information. Starting with the least + * significant bits of 'hdrmask', the bit space is reserved as follows: + * + * 1. 3-bits to indicate the MemoryContextMethodID as defined by + * MEMORY_CONTEXT_METHODID_MASK + * 2. 1-bit to denote an "external" chunk (see below) + * 3. 30-bits reserved for the MemoryContext to use for anything it + * requires. Most MemoryContext likely want to store the size of the + * chunk here. + * 4. 30-bits for the number of bytes that must be subtracted from the chunk + * to obtain the address of the block that the chunk is stored on. + * + * In some cases, for example when memory allocations become large, it's + * possible fields 3 and 4 above are not large enough to store the values + * required for the chunk. In this case, the MemoryContext can choose to mark + * the chunk as "external" by calling the MemoryChunkSetExternal() function. + * When this is done, fields 3 and 4 are unavailable for use by the + * MemoryContext and it's up to the MemoryContext itself to devise its own + * method for getting the reference to the block. + * + * Interface: + * + * MemoryChunkSetHdrMask: + * Used to set up a non-external MemoryChunk. + * + * MemoryChunkSetHdrMaskExternal: + * Used to set up an externally managed MemoryChunk. + * + * MemoryChunkIsExternal: + * Determine if the given MemoryChunk is externally managed, i.e. + * MemoryChunkSetHdrMaskExternal() was called on the chunk. + * + * MemoryChunkGetValue: + * For non-external chunks, return the stored 30-bit value as it was set + * in the call to MemoryChunkSetHdrMask(). + * + * MemoryChunkGetBlock: + * For non-external chunks, return a pointer to the block as it was set + * in the call to MemoryChunkSetHdrMask(). + * + * Also exports: + * MEMORYCHUNK_MAX_VALUE + * MEMORYCHUNK_MAX_BLOCKOFFSET + * PointerGetMemoryChunk + * MemoryChunkGetPointer + * + * Portions Copyright (c) 2022, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * src/include/utils/memutils_memorychunk.h + * + *------------------------------------------------------------------------- + */ + +#ifndef MEMUTILS_MEMORYCHUNK_H +#define MEMUTILS_MEMORYCHUNK_H + +#include "utils/memutils_internal.h" + + /* + * The maximum allowed value that MemoryContexts can store in the value + * field. Must be 1 less than a power of 2. + */ +#define MEMORYCHUNK_MAX_VALUE UINT64CONST(0x3FFFFFFF) + +/* + * The maximum distance in bytes that a MemoryChunk can be offset from the + * block that is storing the chunk. Must be 1 less than a power of 2. + */ +#define MEMORYCHUNK_MAX_BLOCKOFFSET UINT64CONST(0x3FFFFFFF) + +/* define the least significant base-0 bit of each portion of the hdrmask */ +#define MEMORYCHUNK_EXTERNAL_BASEBIT MEMORY_CONTEXT_METHODID_BITS +#define MEMORYCHUNK_VALUE_BASEBIT (MEMORYCHUNK_EXTERNAL_BASEBIT + 1) +#define MEMORYCHUNK_BLOCKOFFSET_BASEBIT (MEMORYCHUNK_VALUE_BASEBIT + 30) + +/* A magic number for storing in the free bits of an external chunk */ +#define MEMORYCHUNK_MAGIC (UINT64CONST(0xB1A8DB858EB6EFBA) >> \ + MEMORYCHUNK_VALUE_BASEBIT << \ + MEMORYCHUNK_VALUE_BASEBIT) + +typedef struct MemoryChunk +{ +#ifdef MEMORY_CONTEXT_CHECKING + Size requested_size; +#endif + + /* bitfield for storing details about the chunk */ + uint64 hdrmask; /* must be last */ +} MemoryChunk; + +/* Get the MemoryChunk from the pointer */ +#define PointerGetMemoryChunk(p) ((MemoryChunk *) ((char *) (p) - sizeof(MemoryChunk))) +/* Get the pointer from the MemoryChunk */ +#define MemoryChunkGetPointer(c) ((void *) ((char *) (c) + sizeof(MemoryChunk))) + +/* private macros for making the inline functions below more simple */ +#define HdrMaskIsExternal(hdrmask) \ + ((hdrmask) & (1 << MEMORYCHUNK_EXTERNAL_BASEBIT)) +#define HdrMaskGetValue(hdrmask) \ + (((hdrmask) >> MEMORYCHUNK_VALUE_BASEBIT) & MEMORYCHUNK_MAX_VALUE) + +/* + * We should have used up all the bits here, so the compiler is likely to + * optimize out the & MEMORYCHUNK_MAX_BLOCKOFFSET. + */ +#define HdrMaskBlockOffset(hdrmask) \ + (((hdrmask) >> MEMORYCHUNK_BLOCKOFFSET_BASEBIT) & MEMORYCHUNK_MAX_BLOCKOFFSET) + +/* For external chunks only, check the magic number matches */ +#define HdrMaskCheckMagic(hdrmask) \ + (MEMORYCHUNK_MAGIC == \ + ((hdrmask) >> MEMORYCHUNK_VALUE_BASEBIT << MEMORYCHUNK_VALUE_BASEBIT)) +/* + * MemoryChunkSetHdrMask + * Store the given 'block', 'chunk_size' and 'methodid' in the given + * MemoryChunk. + * + * The number of bytes between 'block' and 'chunk' must be <= + * MEMORYCHUNK_MAX_BLOCKOFFSET. + * 'value' must be <= MEMORYCHUNK_MAX_VALUE. + */ +static inline void +MemoryChunkSetHdrMask(MemoryChunk *chunk, void *block, + Size value, MemoryContextMethodID methodid) +{ + Size blockoffset = (char *) chunk - (char *) block; + + Assert((char *) chunk > (char *) block); + Assert(blockoffset <= MEMORYCHUNK_MAX_BLOCKOFFSET); + Assert(value <= MEMORYCHUNK_MAX_VALUE); + Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK); + + chunk->hdrmask = (((uint64) blockoffset) << MEMORYCHUNK_BLOCKOFFSET_BASEBIT) | + (((uint64) value) << MEMORYCHUNK_VALUE_BASEBIT) | + methodid; +} + +/* + * MemoryChunkSetHdrMaskExternal + * Set 'chunk' as an externally managed chunk. Here we only record the + * MemoryContextMethodID and set the external chunk bit. + */ +static inline void +MemoryChunkSetHdrMaskExternal(MemoryChunk *chunk, + MemoryContextMethodID methodid) +{ + Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK); + + chunk->hdrmask = MEMORYCHUNK_MAGIC | (((uint64) 1) << MEMORYCHUNK_EXTERNAL_BASEBIT) | + methodid; +} + +/* + * MemoryChunkIsExternal + * Return true if 'chunk' is marked as external. + */ +static inline bool +MemoryChunkIsExternal(MemoryChunk *chunk) +{ + /* + * External chunks should always store MEMORYCHUNK_MAGIC in the upper + * portion of the hdrmask. + */ + Assert(!HdrMaskIsExternal(chunk->hdrmask) || + HdrMaskCheckMagic(chunk->hdrmask)); + + return HdrMaskIsExternal(chunk->hdrmask); +} + +/* + * MemoryChunkGetValue + * For non-external chunks, returns the value field as it was set in + * MemoryChunkSetHdrMask. + */ +static inline Size +MemoryChunkGetValue(MemoryChunk *chunk) +{ + Assert(!HdrMaskIsExternal(chunk->hdrmask)); + + return HdrMaskGetValue(chunk->hdrmask); +} + +/* + * MemoryChunkGetBlock + * For non-external chunks, returns the pointer to the block as was set + * in MemoryChunkSetHdrMask. + */ +static inline void * +MemoryChunkGetBlock(MemoryChunk *chunk) +{ + Assert(!HdrMaskIsExternal(chunk->hdrmask)); + + return (void *) ((char *) chunk - HdrMaskBlockOffset(chunk->hdrmask)); +} + +/* cleanup all internal definitions */ +#undef MEMORYCHUNK_EXTERNAL_BASEBIT +#undef MEMORYCHUNK_VALUE_BASEBIT +#undef MEMORYCHUNK_BLOCKOFFSET_BASEBIT +#undef MEMORYCHUNK_MAGIC +#undef HdrMaskIsExternal +#undef HdrMaskGetValue +#undef HdrMaskBlockOffset +#undef HdrMaskCheckMagic + +#endif /* MEMUTILS_MEMORYCHUNK_H */ diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index a4a4e356e5..51a3e719e6 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -57,6 +57,7 @@ AlenState Alias AllocBlock AllocChunk +AllocFreelistLink AllocPointer AllocSet AllocSetContext @@ -1522,12 +1523,14 @@ MemoizeKey MemoizePath MemoizeState MemoizeTuple +MemoryChunk MemoryContext MemoryContextCallback MemoryContextCallbackFunction MemoryContextCounters MemoryContextData MemoryContextMethods +MemoryContextMethodID MemoryStatsPrintFunc MergeAction MergeActionState -- 2.34.1
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 05:26  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 2 replies; 152+ messages in thread

From: David Rowley @ 2022-08-29 05:26 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Mon, 29 Aug 2022 at 10:39, David Rowley <dgrowleyml@gmail.com> wrote:
> One more try to make CFbot happy.

After a bit more revision, mostly updating outdated comments and
naming adjustments, I've pushed this.

Per the benchmark results I showed in [1], due to the performance of
having the AllocSet free list pointers stored at the end of the
allocated chunk being quite a bit slower than having them at the start
of the chunk, I adjusted the patch to have them at the start.

Time for me to go and watch the buildfarm results come in.

David

[1] https://postgr.es/m/CAApHDvpuhcPWCzkXZuQQgB8YjPNQSvnncbzZ6pwpHFr2QMMD2w@mail.gmail.com





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 09:37  Amit Kapila <amit.kapila16@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 2 replies; 152+ messages in thread

From: Amit Kapila @ 2022-08-29 09:37 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Mon, Aug 29, 2022 at 10:57 AM David Rowley <dgrowleyml@gmail.com> wrote:
>
> After a bit more revision, mostly updating outdated comments and
> naming adjustments, I've pushed this.
>
> Per the benchmark results I showed in [1], due to the performance of
> having the AllocSet free list pointers stored at the end of the
> allocated chunk being quite a bit slower than having them at the start
> of the chunk, I adjusted the patch to have them at the start.
>
> Time for me to go and watch the buildfarm results come in.
>

There is a BF failure with a callstack:
2022-08-29 03:29:56.911 EDT [1056:67] pg_regress/ddl STATEMENT:
SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL,
NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
TRAP: FailedAssertion("pointer == (void *) MAXALIGN(pointer)", File:
"../../../../src/include/utils/memutils_internal.h", Line: 120, PID:
1056)
0x1e6f71c <ExceptionalCondition+0x9c> at postgres
0x1ea8494 <MemoryContextAllowInCriticalSection.part.0> at postgres
0x1ea9ee8 <repalloc> at postgres
0x1c56dc4 <ReorderBufferCleanupTXN+0xbc> at postgres
0x1c58a1c <ReorderBufferProcessTXN+0x1980> at postgres
0x1c44c5c <xact_decode+0x46c> at postgres
0x1c445f0 <LogicalDecodingProcessRecord+0x98> at postgres
0x1c4b578 <pg_logical_slot_get_changes_guts+0x318> at postgres
0x1ad69ec <ExecMakeTableFunctionResult+0x268> at postgres
0x1aedc88 <FunctionNext+0x3a0> at postgres
0x1ad7808 <ExecScan+0x100> at postgres
0x1acaaa0 <standard_ExecutorRun+0x158> at postgres
0x1ceac3c <PortalRunSelect+0x2d0> at postgres
0x1cec8ec <PortalRun+0x16c> at postgres
0x1ce7b30 <exec_simple_query+0x3a4> at postgres
0x1ce96ec <PostgresMain+0x1720> at postgres
0x1c2c784 <PostmasterMain+0x1a3c> at postgres
0x1ee6a1c <main+0x248> at postgres

I am not completely sure if the failure is due to your commit but it
was showing the line added by this commit. Note that I had also
committed (commit id: d2169c9985) one patch today but couldn't
correlate the failure with that so thought of checking with you. There
are other similar failures[2][3] as well but [1] shows the stack
trace. Any idea?

[1] - https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mamba&dt=2022-08-29%2005%3A53%3A57
[2] - https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=grison&dt=2022-08-29%2008%3A13%3A09
[3] - https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=skate&dt=2022-08-29%2006%3A13%3A24

-- 
With Regards,
Amit Kapila.





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 09:42  David Rowley <dgrowleyml@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  1 sibling, 0 replies; 152+ messages in thread

From: David Rowley @ 2022-08-29 09:42 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Mon, 29 Aug 2022 at 21:37, Amit Kapila <amit.kapila16@gmail.com> wrote:
> I am not completely sure if the failure is due to your commit but it
> was showing the line added by this commit. Note that I had also
> committed (commit id: d2169c9985) one patch today but couldn't
> correlate the failure with that so thought of checking with you. There
> are other similar failures[2][3] as well but [1] shows the stack
> trace. Any idea?

I'm currently suspecting that I broke it.  I'm thinking it was just an
unfortunate coincidence that you made some changes to test_decoding
shortly before.

I'm currently seeing it I can recreate this on a Raspberry PI.

David

> [1] - https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mamba&dt=2022-08-29%2005%3A53%3A57
> [2] - https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=grison&dt=2022-08-29%2008%3A13%3A09
> [3] - https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=skate&dt=2022-08-29%2006%3A13%3A24





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 11:10  David Rowley <dgrowleyml@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  1 sibling, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-08-29 11:10 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Mon, 29 Aug 2022 at 21:37, Amit Kapila <amit.kapila16@gmail.com> wrote:
> 2022-08-29 03:29:56.911 EDT [1056:67] pg_regress/ddl STATEMENT:
> SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL,
> NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
> TRAP: FailedAssertion("pointer == (void *) MAXALIGN(pointer)", File:
> "../../../../src/include/utils/memutils_internal.h", Line: 120, PID:
> 1056)

I suspect, going by all 3 failing animals being 32-bit which have a
MAXIMUM_ALIGNOF 8 and SIZEOF_SIZE_T of 4 that this is due to the lack
of padding in the MemoryChunk struct.

AllocChunkData and GenerationChunk had padding to account for
sizeof(Size) being 4 and sizeof(void *) being 8, I didn't add that to
MemoryChunk, so I'll do that now.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 13:47  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-08-29 13:47 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> I suspect, going by all 3 failing animals being 32-bit which have a
> MAXIMUM_ALIGNOF 8 and SIZEOF_SIZE_T of 4 that this is due to the lack
> of padding in the MemoryChunk struct.
> AllocChunkData and GenerationChunk had padding to account for
> sizeof(Size) being 4 and sizeof(void *) being 8, I didn't add that to
> MemoryChunk, so I'll do that now.

Doesn't seem to have fixed it.  IMO, the fact that we can get through
core regression tests and pg_upgrade is a strong indicator that
there's not anything fundamentally wrong with memory context
management.  I'm inclined to think the problem is in d2169c9985,
instead ... though I can't see anything wrong with it.

Another possibility is that there's a pre-existing bug in the
logical decoding stuff that your changes accidentally exposed.
I wonder if valgrind would show anything interesting.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 14:02  Amit Kapila <amit.kapila16@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 2 replies; 152+ messages in thread

From: Amit Kapila @ 2022-08-29 14:02 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: David Rowley <dgrowleyml@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Mon, Aug 29, 2022 at 7:17 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> David Rowley <dgrowleyml@gmail.com> writes:
> > I suspect, going by all 3 failing animals being 32-bit which have a
> > MAXIMUM_ALIGNOF 8 and SIZEOF_SIZE_T of 4 that this is due to the lack
> > of padding in the MemoryChunk struct.
> > AllocChunkData and GenerationChunk had padding to account for
> > sizeof(Size) being 4 and sizeof(void *) being 8, I didn't add that to
> > MemoryChunk, so I'll do that now.
>
> Doesn't seem to have fixed it.  IMO, the fact that we can get through
> core regression tests and pg_upgrade is a strong indicator that
> there's not anything fundamentally wrong with memory context
> management.  I'm inclined to think the problem is in d2169c9985,
> instead ... though I can't see anything wrong with it.
>

Yeah, I also thought that way but couldn't find a reason. I think if
David is able to reproduce it on one of his systems then he can try
locally reverting both the commits one by one.

> Another possibility is that there's a pre-existing bug in the
> logical decoding stuff that your changes accidentally exposed.
>

Yeah, this is another possibility.

-- 
With Regards,
Amit Kapila.





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 14:52  Tomas Vondra <tomas.vondra@enterprisedb.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  1 sibling, 1 reply; 152+ messages in thread

From: Tomas Vondra @ 2022-08-29 14:52 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; +Cc: David Rowley <dgrowleyml@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>



On 8/29/22 16:02, Amit Kapila wrote:
> On Mon, Aug 29, 2022 at 7:17 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>>
>> David Rowley <dgrowleyml@gmail.com> writes:
>>> I suspect, going by all 3 failing animals being 32-bit which have a
>>> MAXIMUM_ALIGNOF 8 and SIZEOF_SIZE_T of 4 that this is due to the lack
>>> of padding in the MemoryChunk struct.
>>> AllocChunkData and GenerationChunk had padding to account for
>>> sizeof(Size) being 4 and sizeof(void *) being 8, I didn't add that to
>>> MemoryChunk, so I'll do that now.
>>
>> Doesn't seem to have fixed it.  IMO, the fact that we can get through
>> core regression tests and pg_upgrade is a strong indicator that
>> there's not anything fundamentally wrong with memory context
>> management.  I'm inclined to think the problem is in d2169c9985,
>> instead ... though I can't see anything wrong with it.
>>
> 
> Yeah, I also thought that way but couldn't find a reason. I think if
> David is able to reproduce it on one of his systems then he can try
> locally reverting both the commits one by one.
> 

I can reproduce it on my system (rpi4 running 32-bit raspbian). I can't
grant access very easily at the moment, so I'll continue investigating
do more debugging on perhaps I can grant access to the system.

So far all I know is that it doesn't happen on d2169c9985 (so ~5 commits
back), and then it starts failing on c6e0fe1f2a. The extra padding added
by df0f4feef8 makes no difference, because the struct looked like this:

    struct MemoryChunk {
        Size                       requested_size;  /*     0     4 */

        /* XXX 4 bytes hole, try to pack */

        uint64                     hdrmask;         /*     8     8 */

        /* size: 16, cachelines: 1, members: 2 */
        /* sum members: 12, holes: 1, sum holes: 4 */
        /* last cacheline: 16 bytes */
    };

and the padding makes it look like this:

    struct MemoryChunk {
        Size                       requested_size;  /*     0     4 */
        char                       padding[4];      /*     4     8 */
        uint64                     hdrmask;         /*     8     8 */

        /* size: 16, cachelines: 1, members: 2 */
        /* sum members: 12, holes: 1, sum holes: 4 */
        /* last cacheline: 16 bytes */
    };

so it makes no difference.

I did look at the pointers in GetMemoryChunkMethodID, and it looks like
this (p1 is result of MAXALIGN(pointer):

(gdb) p pointer
$1 = (void *) 0x1ca1d2c
(gdb) p p1
$2 = 0x1ca1d30 ""
(gdb) p p1 - pointer
$3 = 4
(gdb) p (long int) pointer
$4 = 30022956
(gdb) p (long int) p1
$5 = 30022960
(gdb) p 30022956 % 8
$6 = 4

So the input pointer is not actually aligned to MAXIMUM_ALIGNOF (8B),
but only to 4B. That seems a bit strange.


>> Another possibility is that there's a pre-existing bug in the
>> logical decoding stuff that your changes accidentally exposed.
>>
> 
> Yeah, this is another possibility.

No idea.


regards

-- 
Tomas Vondra
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 14:55  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  1 sibling, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-08-29 14:55 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: David Rowley <dgrowleyml@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Amit Kapila <amit.kapila16@gmail.com> writes:
> Yeah, I also thought that way but couldn't find a reason. I think if
> David is able to reproduce it on one of his systems then he can try
> locally reverting both the commits one by one.

It seems to repro easily on any 32-bit platform.  Aside from the
buildfarm results, I've now duplicated it on 32-bit ARM (which
eliminates the possibility that it's big-endian specific).

"bt full" from the first crash gives

#0  0xb6d7126c in raise () from /lib/libc.so.6
No symbol table info available.
#1  0xb6d5c360 in abort () from /lib/libc.so.6
No symbol table info available.
#2  0x00572430 in ExceptionalCondition (
    conditionName=conditionName@entry=0x745110 "pointer == (void *) MAXALIGN(pointer)", errorType=errorType@entry=0x5d18d0 "FailedAssertion", 
    fileName=fileName@entry=0x7450dc "../../../../src/include/utils/memutils_internal.h", lineNumber=lineNumber@entry=120) at assert.c:69
No locals.
#3  0x005a0d90 in GetMemoryChunkMethodID (pointer=<optimized out>)
    at ../../../../src/include/utils/memutils_internal.h:120
        header = <optimized out>
#4  0x005a231c in GetMemoryChunkMethodID (pointer=<optimized out>)
    at ../../../../src/include/utils/memutils_internal.h:119
        header = <optimized out>
        header = <optimized out>
#5  pfree (pointer=<optimized out>) at mcxt.c:1242
No locals.
#6  0x003c8fdc in ReorderBufferCleanupTXN (rb=0x7450dc, rb@entry=0x1f, 
    txn=0x745110, txn@entry=0xe1f800) at reorderbuffer.c:1493
        change = <optimized out>
        found = false
        iter = {cur = <optimized out>, next = 0xddcb18, end = 0xde4e64}
#7  0x003ca968 in ReorderBufferProcessTXN (rb=0x1f, rb@entry=0xe1f800, 
    txn=0xe1f800, commit_lsn=<optimized out>, snapshot_now=<optimized out>, 
    command_id=<optimized out>, streaming=false) at reorderbuffer.c:2514
        change = 0x0
        _save_exception_stack = 0x0
        _save_context_stack = 0x1
        _local_sigjmp_buf = {{__jmpbuf = {-552117431, 1640676937, -1092521468, 
              14569068, 14569068, 14568932, 729, 0, 228514434, 166497, 0, 
              8195960, 8196088, 7, 0 <repeats 13 times>, 13847224, 0, 196628, 
              0, 1844909312, 5178548, -1092520644, 13979392, 13979388, 
              14801472, 0, 8195960, 8196088, 7, 0, 8108342, 8108468, 1, 
              715827883, -1030792151, 0, 8195960, 729, 7, 0, 14809088, 
              14809088, 14542436, 0, 26303888, 0, 14568932, 3978796, 156, 0, 
              1, 0}, __mask_was_saved = 0, __saved_mask = {__val = {64, 
                7242472, 14740696, 7244624, 14809088, 14741512, 5, 14740696, 
                7244624, 7245864, 3982844, 14542436, 0, 14809092, 0, 26303888, 
                729, 14569112, 14809092, 7242472, 729, 14741512, 32, 14809088, 
                0, 228514434, 166497, 0, 0, 26303888, 3980968, 0}}}}
        _do_rethrow = <optimized out>
        using_subtxn = 228
        ccxt = 0x7aae68 <my_wait_event_info>
        iterstate = 0x0
        prev_lsn = 26303888
        specinsert = 0x0
        stream_started = false
        curtxn = 0x0
        __func__ = "ReorderBufferProcessTXN"
#8  0x003cb460 in ReorderBufferReplay (txn=<optimized out>, 
    rb=rb@entry=0xe1f800, commit_lsn=<optimized out>, end_lsn=<optimized out>, 
    commit_time=715099169882112, origin_id=0, origin_lsn=0, xid=729)
    at reorderbuffer.c:2641
        snapshot_now = <optimized out>
#9  0x003cbedc in ReorderBufferCommit (rb=rb@entry=0xe1f800, 
    xid=xid@entry=729, commit_lsn=<optimized out>, end_lsn=<optimized out>, 
    commit_time=<optimized out>, commit_time@entry=715099398396546, 
    origin_id=<optimized out>, origin_id@entry=0, origin_lsn=0, 
    origin_lsn@entry=5906902891454464) at reorderbuffer.c:2665
        txn = <optimized out>
#10 0x003bb19c in DecodeCommit (two_phase=false, xid=729, parsed=0xbee17478, 
    buf=<optimized out>, ctx=0xe1d7f8) at decode.c:682
        origin_lsn = <optimized out>
        commit_time = <optimized out>
        origin_id = 0
        i = <optimized out>
        origin_lsn = <optimized out>
        commit_time = <optimized out>
        origin_id = <optimized out>
        i = <optimized out>
#11 xact_decode (ctx=0xe1d7f8, buf=<optimized out>) at decode.c:216
        xlrec = <optimized out>
        parsed = {xact_time = 715099398396546, xinfo = 73, dbId = 16384, 
          tsId = 1663, nsubxacts = 0, subxacts = 0x0, nrels = 0, 
          xlocators = 0x0, nstats = 0, stats = 0x0, nmsgs = 70, 
          msgs = 0xe2b828, twophase_xid = 0, 
          twophase_gid = '\000' <repeats 199 times>, nabortrels = 0, 
          abortlocators = 0x0, nabortstats = 0, abortstats = 0x0, 
          origin_lsn = 0, origin_timestamp = 0}
        xid = <optimized out>
        two_phase = false
        builder = <optimized out>
        reorder = <optimized out>
        r = <optimized out>
        info = <optimized out>
        __func__ = "xact_decode"
#12 0x003babf0 in LogicalDecodingProcessRecord (ctx=ctx@entry=0xe1d7f8, 
    record=0xe1dad0) at decode.c:119
        buf = {origptr = 26303888, endptr = 26305088, record = 0xe1dad0}
        txid = <optimized out>
        rmgr = <optimized out>
#13 0x003c0390 in pg_logical_slot_get_changes_guts (fcinfo=0x0, 
    confirm=<optimized out>, binary=<optimized out>) at logicalfuncs.c:271
        record = <optimized out>
        errm = 0x0
        _save_exception_stack = 0xd60380
        _save_context_stack = 0x1
        _local_sigjmp_buf = {{__jmpbuf = {-552117223, 1640638557, 4, 14770368, 
              -1092519792, -1, 14770320, 8, 1, 14691520, 0, 8195960, 8196088, 
              7, 0 <repeats 12 times>, 3398864, 0, 13849464, 13848680, 
              14650600, 3399100, 4, 3125412, 0, 144, 0, 0, 8192, 7616300, 0, 
              1576, 7616452, 14585296, 8192, 7616300, 14651128, 0, 0, 
              14651128, -1092519880, 3398864, 0, 13849464, 13848680, 3399100, 
              0, 5904972, 8112272, -1, 14591624, -1375937000, -1375937248, 
              14591376}, __mask_was_saved = 0, __saved_mask = {__val = {
                14530312, 14528852, 2348328335, 14527224, 5699140, 3202447388, 
                4, 14527080, 5699156, 14530312, 5769228, 2918792552, 0, 0, 0, 
                14767888, 3067834868, 14591600, 13824008, 1023, 3068719720, 1, 
                184, 14589688, 14586024, 14587400, 14691504, 14586024, 
                14585752, 14586200, 2615480, 8112268}}}}
        _do_rethrow = <optimized out>
        name = 0xe16090
        upto_lsn = 3933972
        upto_nchanges = 14707744
        rsinfo = <optimized out>
        per_query_ctx = <optimized out>
        oldcontext = 0xe06cc0
        end_of_wal = 0
        ctx = 0xe1d7f8
        old_resowner = 0xd35568
        arr = <optimized out>
        ndim = <optimized out>
        options = 0x0
        p = 0xe02cb0
        __func__ = "pg_logical_slot_get_changes_guts"
#14 0x00292864 in ExecMakeTableFunctionResult (setexpr=0xdea9b0, 
    econtext=0xde90a8, argContext=<optimized out>, expectedDesc=0x1, 
    randomAccess=false) at execSRF.c:234
        result = 2590380
        tupstore = 0x0
        tupdesc = 0x0
        funcrettype = 8040208
        returnsTuple = <optimized out>
        returnsSet = 32
        fcinfo = 0xe02cb0
        fcusage = {fs = 0x0, save_f_total_time = {tv_sec = 14592432, 
            tv_nsec = 7093408}, save_total = {tv_sec = 0, tv_nsec = 0}, 
          f_start = {tv_sec = 14767936, tv_nsec = 14767940}}
        rsinfo = {type = T_ReturnSetInfo, econtext = 0xde90a8, 
          expectedDesc = 0xdea7a0, allowedModes = 11, 
          returnMode = SFRM_Materialize, isDone = ExprSingleResult, 
          setResult = 0xe16548, setDesc = 0xe16338}
        tmptup = {t_len = 3, t_self = {ip_blkid = {bi_hi = 0, bi_lo = 0}, 
            ip_posid = 0}, t_tableOid = 0, t_data = 0x3}
        callerContext = 0xdea7a0
        first_time = true
        __func__ = "ExecMakeTableFunctionResult"
... etc ...

Anything ring a bell?

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 15:15  Robert Haas <robertmhaas@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 2 replies; 152+ messages in thread

From: Robert Haas @ 2022-08-29 15:15 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; David Rowley <dgrowleyml@gmail.com>; Andres Freund <andres@anarazel.de>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Hi,

I've got another problem with this patch here on macOS:

ccache clang -Wall -Wmissing-prototypes -Wpointer-arith
-Wdeclaration-after-statement -Werror=vla
-Werror=unguarded-availability-new -Wendif-labels
-Wmissing-format-attribute -Wformat-security -fno-strict-aliasing
-fwrapv -Wno-unused-command-line-argument -g -O2 -Wall -Werror
-Wno-unknown-warning-option -fno-omit-frame-pointer
-I../../../../src/include  -isysroot
/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk
-I/opt/local/include/libxml2 -I/opt/local/include -I/opt/local/include
 -I/opt/local/include  -c -o aset.o aset.c -MMD -MP -MF .deps/aset.Po
In file included from aset.c:52:
../../../../src/include/utils/memutils_memorychunk.h:170:18: error:
comparison of constant 7 with expression of type
'MemoryContextMethodID' (aka 'enum MemoryContextMethodID') is always
true [-Werror,-Wtautological-constant-out-of-range-compare]
        Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK);
        ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../../../../src/include/c.h:827:9: note: expanded from macro 'Assert'
                if (!(condition)) \
                      ^~~~~~~~~
In file included from aset.c:52:
../../../../src/include/utils/memutils_memorychunk.h:186:18: error:
comparison of constant 7 with expression of type
'MemoryContextMethodID' (aka 'enum MemoryContextMethodID') is always
true [-Werror,-Wtautological-constant-out-of-range-compare]
        Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK);
        ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../../../../src/include/c.h:827:9: note: expanded from macro 'Assert'
                if (!(condition)) \
                      ^~~~~~~~~

I'm not sure what to do about that, but every file that includes
memutils_memorychunk.h produces those warnings (which become errors
due to -Werror).

...Robert





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 15:20  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Tomas Vondra <tomas.vondra@enterprisedb.com>
  0 siblings, 3 replies; 152+ messages in thread

From: Tom Lane @ 2022-08-29 15:20 UTC (permalink / raw)
  To: Tomas Vondra <tomas.vondra@enterprisedb.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; David Rowley <dgrowleyml@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Tomas Vondra <tomas.vondra@enterprisedb.com> writes:
> I can reproduce it on my system (rpi4 running 32-bit raspbian).

Yeah, more or less same as what I'm testing on.

Seeing that the complaint is about pfree'ing a non-maxaligned
ReorderBufferChange pointer, I tried adding

inline patch 1: src/backend/replication/logical/reorderbuffer.c (+2/-0 lines) download inline-1.patchdiff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c index 89cf9f9389..dfa9b6c9ee 100644 --- a/src/backend/replication/logical/reorderbuffer.c +++ b/src/backend/replication/logical/reorderbuffer.c @@ -472,6 +472,8 @@ ReorderBufferGetChange(ReorderBuffer *rb) change = (ReorderBufferChange *) MemoryContextAlloc(rb->change_context, sizeof(ReorderBufferChange)); + Assert(change == (void *) MAXALIGN(change)); + memset(change, 0, sizeof(ReorderBufferChange)); return change; }
and this failed! (gdb) f 3 #3 0x003cb888 in ReorderBufferGetChange (rb=0x24ed820) at reorderbuffer.c:475 475 Assert(change == (void *) MAXALIGN(change)); (gdb) p change $1 = (ReorderBufferChange *) 0x24aaa14 So the bug is in fact in David's changes, and it consists in palloc sometimes handing back non-maxaligned pointers. I find it mildly astonishing that we managed to get through core regression tests without such a fault surfacing, but there you have it. This machine has MAXALIGN 8 but 4-byte pointers, so there's something wrong with that situation. regards, tom lane ^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 15:25  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  2 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-08-29 15:25 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

I wrote:
> So the bug is in fact in David's changes, and it consists in palloc
> sometimes handing back non-maxaligned pointers.  I find it mildly
> astonishing that we managed to get through core regression tests
> without such a fault surfacing, but there you have it.

Oh!  I just noticed that the troublesome context (rb->change_context)
is a SlabContext, so it may be that this only happens in non-aset
contexts.  It's a lot easier to believe that the core tests never
exercise the case of pfree'ing a slab chunk.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 15:27  Tomas Vondra <tomas.vondra@enterprisedb.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  2 siblings, 1 reply; 152+ messages in thread

From: Tomas Vondra @ 2022-08-29 15:27 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; David Rowley <dgrowleyml@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>



On 8/29/22 17:20, Tom Lane wrote:
> Tomas Vondra <tomas.vondra@enterprisedb.com> writes:
>> I can reproduce it on my system (rpi4 running 32-bit raspbian).
> 
> Yeah, more or less same as what I'm testing on.
> 
> Seeing that the complaint is about pfree'ing a non-maxaligned
> ReorderBufferChange pointer, I tried adding
> 
> diff --git a/src/backend/replication/logical/reorderbuffer.c b/src/backend/replication/logical/reorderbuffer.c
> index 89cf9f9389..dfa9b6c9ee 100644
> --- a/src/backend/replication/logical/reorderbuffer.c
> +++ b/src/backend/replication/logical/reorderbuffer.c
> @@ -472,6 +472,8 @@ ReorderBufferGetChange(ReorderBuffer *rb)
>         change = (ReorderBufferChange *)
>                 MemoryContextAlloc(rb->change_context, sizeof(ReorderBufferChange));
>  
> +       Assert(change == (void *) MAXALIGN(change));
> +
>         memset(change, 0, sizeof(ReorderBufferChange));
>         return change;
>  }
> 
> and this failed!
> 
> (gdb) f 3
> #3  0x003cb888 in ReorderBufferGetChange (rb=0x24ed820) at reorderbuffer.c:475
> 475             Assert(change == (void *) MAXALIGN(change));
> (gdb) p change
> $1 = (ReorderBufferChange *) 0x24aaa14
> 
> So the bug is in fact in David's changes, and it consists in palloc
> sometimes handing back non-maxaligned pointers.  I find it mildly
> astonishing that we managed to get through core regression tests
> without such a fault surfacing, but there you have it.
> 
> This machine has MAXALIGN 8 but 4-byte pointers, so there's something
> wrong with that situation.
> 

I suspect it's a pre-existing bug in Slab allocator, because it does this:

#define SlabBlockGetChunk(slab, block, idx) \
	((MemoryChunk *) ((char *) (block) + sizeof(SlabBlock)	\
					+ (idx * slab->fullChunkSize)))

and SlabBlock is only 20B, i.e. not a multiple of 8B. Which would mean
that even if we allocate block and size the chunks carefully (with all
the MAXALIGN things), we ultimately slice the block incorrectly.

This would explain the 4B difference I reported before, I think. But I'm
just as astonished we got this far in the tests - regular regression
tests don't do much logical decoding, and we only use slab for changes,
but I see the failure in 006 test in src/test/recovery, so the first
five completed fine.


regards

-- 
Tomas Vondra
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 15:31  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 0 replies; 152+ messages in thread

From: Tom Lane @ 2022-08-29 15:31 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; David Rowley <dgrowleyml@gmail.com>; Andres Freund <andres@anarazel.de>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Robert Haas <robertmhaas@gmail.com> writes:
> I've got another problem with this patch here on macOS:

> In file included from aset.c:52:
> ../../../../src/include/utils/memutils_memorychunk.h:170:18: error:
> comparison of constant 7 with expression of type
> 'MemoryContextMethodID' (aka 'enum MemoryContextMethodID') is always
> true [-Werror,-Wtautological-constant-out-of-range-compare]
>         Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK);
>         ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> ../../../../src/include/c.h:827:9: note: expanded from macro 'Assert'
>                 if (!(condition)) \
>                       ^~~~~~~~~

Huh.  My macOS buildfarm animals aren't showing that, nor can I
repro it on my laptop.  Which compiler version are you using exactly?

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 15:39  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-08-29 15:39 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Got it: sizeof(SlabBlock) isn't a multiple of MAXALIGN,

(gdb) p sizeof(SlabBlock)
$4 = 20

but this coding requires it to be:

#define SlabBlockGetChunk(slab, block, idx) \
	((MemoryChunk *) ((char *) (block) + sizeof(SlabBlock)	\
					+ (idx * slab->fullChunkSize)))

So what you actually need to do is add some alignment padding to
SlabBlock.  I'd suggest reverting df0f4feef as it seems to be
a red herring.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 15:39  Tomas Vondra <tomas.vondra@enterprisedb.com>
  parent: Tomas Vondra <tomas.vondra@enterprisedb.com>
  0 siblings, 1 reply; 152+ messages in thread

From: Tomas Vondra @ 2022-08-29 15:39 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; David Rowley <dgrowleyml@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On 8/29/22 17:27, Tomas Vondra wrote:
> ...
>
> I suspect it's a pre-existing bug in Slab allocator, because it does this:
> 
> #define SlabBlockGetChunk(slab, block, idx) \
> 	((MemoryChunk *) ((char *) (block) + sizeof(SlabBlock)	\
> 					+ (idx * slab->fullChunkSize)))
> 
> and SlabBlock is only 20B, i.e. not a multiple of 8B. Which would mean
> that even if we allocate block and size the chunks carefully (with all
> the MAXALIGN things), we ultimately slice the block incorrectly.
> 

The attached patch seems to fix the issue for me - at least it seems
like that. This probably will need to get backpatched, I guess. Maybe we
should add an assert to MemoryChunkGetPointer to check alignment?



> This would explain the 4B difference I reported before, I think. But I'm
> just as astonished we got this far in the tests - regular regression
> tests don't do much logical decoding, and we only use slab for changes,
> but I see the failure in 006 test in src/test/recovery, so the first
> five completed fine.
> 

I got confused - the first 5 tests in src/test/recovery don't do any
logical decoding, so it's not surprising it's the 006 that fails.

regards

-- 
Tomas Vondra
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

Attachments:

slab-fix.patch (text/x-patch, 1.4K) download diff --git a/src/backend/utils/mmgr/slab.c b/src/backend/utils/mmgr/slab.c index ae1a735b8c..67fbede836 100644 --- a/src/backend/utils/mmgr/slab.c +++ b/src/backend/utils/mmgr/slab.c @@ -102,10 +102,10 @@ typedef struct SlabBlock #define SlabChunkGetPointer(chk) \ ((void *)(((char *)(chk)) + sizeof(MemoryChunk))) #define SlabBlockGetChunk(slab, block, idx) \ - ((MemoryChunk *) ((char *) (block) + sizeof(SlabBlock) \ + ((MemoryChunk *) ((char *) (block) + MAXALIGN(sizeof(SlabBlock)) \ + (idx * slab->fullChunkSize))) #define SlabBlockStart(block) \ - ((char *) block + sizeof(SlabBlock)) + ((char *) block + MAXALIGN(sizeof(SlabBlock))) #define SlabChunkIndex(slab, block, chunk) \ (((char *) chunk - SlabBlockStart(block)) / slab->fullChunkSize) @@ -146,12 +146,12 @@ SlabContextCreate(MemoryContext parent, fullChunkSize = Slab_CHUNKHDRSZ + MAXALIGN(chunkSize); /* Make sure the block can store at least one chunk. */ - if (blockSize < fullChunkSize + sizeof(SlabBlock)) + if (blockSize < fullChunkSize + MAXALIGN(sizeof(SlabBlock))) elog(ERROR, "block size %zu for slab is too small for %zu chunks", blockSize, chunkSize); /* Compute maximum number of chunks per block */ - chunksPerBlock = (blockSize - sizeof(SlabBlock)) / fullChunkSize; + chunksPerBlock = (blockSize - MAXALIGN(sizeof(SlabBlock))) / fullChunkSize; /* The freelist starts with 0, ends with chunksPerBlock. */ freelistSize = sizeof(dlist_head) * (chunksPerBlock + 1);
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 15:43  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  2 siblings, 4 replies; 152+ messages in thread

From: Tom Lane @ 2022-08-29 15:43 UTC (permalink / raw)
  To: Tomas Vondra <tomas.vondra@enterprisedb.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; David Rowley <dgrowleyml@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Tomas Vondra <tomas.vondra@enterprisedb.com> writes:
> I suspect it's a pre-existing bug in Slab allocator, because it does this:

> #define SlabBlockGetChunk(slab, block, idx) \
> 	((MemoryChunk *) ((char *) (block) + sizeof(SlabBlock)	\
> 					+ (idx * slab->fullChunkSize)))

> and SlabBlock is only 20B, i.e. not a multiple of 8B. Which would mean
> that even if we allocate block and size the chunks carefully (with all
> the MAXALIGN things), we ultimately slice the block incorrectly.

Right, same conclusion I just came to.  But it's not a "pre-existing"
bug, because sizeof(SlabBlock) *was* maxaligned until David added
another field to it.

I think adding a padding field to SlabBlock would be a less messy
solution than your patch.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 15:57  Andres Freund <andres@anarazel.de>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  3 siblings, 1 reply; 152+ messages in thread

From: Andres Freund @ 2022-08-29 15:57 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; David Rowley <dgrowleyml@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2022-08-29 11:43:14 -0400, Tom Lane wrote:
> Tomas Vondra <tomas.vondra@enterprisedb.com> writes:
> > I suspect it's a pre-existing bug in Slab allocator, because it does this:
> 
> > #define SlabBlockGetChunk(slab, block, idx) \
> > 	((MemoryChunk *) ((char *) (block) + sizeof(SlabBlock)	\
> > 					+ (idx * slab->fullChunkSize)))
> 
> > and SlabBlock is only 20B, i.e. not a multiple of 8B. Which would mean
> > that even if we allocate block and size the chunks carefully (with all
> > the MAXALIGN things), we ultimately slice the block incorrectly.
> 
> Right, same conclusion I just came to.  But it's not a "pre-existing"
> bug, because sizeof(SlabBlock) *was* maxaligned until David added
> another field to it.
> 
> I think adding a padding field to SlabBlock would be a less messy
> solution than your patch.

That just seems to invite the same problem happening again later and it's
harder to ensure that the padding is correct across platforms.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 16:00  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 0 replies; 152+ messages in thread

From: Tom Lane @ 2022-08-29 16:00 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; David Rowley <dgrowleyml@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Andres Freund <andres@anarazel.de> writes:
> On 2022-08-29 11:43:14 -0400, Tom Lane wrote:
>> I think adding a padding field to SlabBlock would be a less messy
>> solution than your patch.

> That just seems to invite the same problem happening again later and it's
> harder to ensure that the padding is correct across platforms.

Yeah, I just tried and failed to write a general padding computation
--- you can't use sizeof() in the #if, which makes it a lot more
fragile than I was expecting.  Tomas' way is probably the best.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 16:00  Tomas Vondra <tomas.vondra@enterprisedb.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  3 siblings, 0 replies; 152+ messages in thread

From: Tomas Vondra @ 2022-08-29 16:00 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; David Rowley <dgrowleyml@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>



On 8/29/22 17:43, Tom Lane wrote:
> Tomas Vondra <tomas.vondra@enterprisedb.com> writes:
>> I suspect it's a pre-existing bug in Slab allocator, because it does this:
> 
>> #define SlabBlockGetChunk(slab, block, idx) \
>> 	((MemoryChunk *) ((char *) (block) + sizeof(SlabBlock)	\
>> 					+ (idx * slab->fullChunkSize)))
> 
>> and SlabBlock is only 20B, i.e. not a multiple of 8B. Which would mean
>> that even if we allocate block and size the chunks carefully (with all
>> the MAXALIGN things), we ultimately slice the block incorrectly.
> 
> Right, same conclusion I just came to.  But it's not a "pre-existing"
> bug, because sizeof(SlabBlock) *was* maxaligned until David added
> another field to it.
> 

Yeah, that's true. Still, there was an implicit expectation the size is
maxaligned, but it wasn't mentioned anywhere. I don't even recall if I
was aware of it when I wrote that code, or if I was just lucky.

> I think adding a padding field to SlabBlock would be a less messy
> solution than your patch.

Maybe, although I find it a bit annoying that we do MAXALIGN() for a
bunch of structs, and then in other places we add padding. Maybe not for
Slab, but e.g. for Generation. Maybe we should try doing the same thing
in all those places.

regards

-- 
Tomas Vondra
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 21:55  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  3 siblings, 0 replies; 152+ messages in thread

From: David Rowley @ 2022-08-29 21:55 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; Tomas Vondra <tomas.vondra@enterprisedb.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 30 Aug 2022 at 03:43, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> I think adding a padding field to SlabBlock would be a less messy
> solution than your patch.

Thank you both of you for looking at this while I was sleeping.

I've read over the emails and glanced at Tomas' patch. I think that
seems good. I think I'd rather see us do that than pad the struct out
further as Tomas' method is more aligned to what we do in aset.c
(ALLOC_BLOCKHDRSZ) and generation.c (Generation_BLOCKHDRSZ).

I can adjust Tomas' patch to #define Slab_BLOCKHDRSZ

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-29 21:57  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  3 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-08-29 21:57 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> I've read over the emails and glanced at Tomas' patch. I think that
> seems good. I think I'd rather see us do that than pad the struct out
> further as Tomas' method is more aligned to what we do in aset.c
> (ALLOC_BLOCKHDRSZ) and generation.c (Generation_BLOCKHDRSZ).

> I can adjust Tomas' patch to #define Slab_BLOCKHDRSZ

WFM

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 00:22  Tomas Vondra <tomas.vondra@enterprisedb.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: Tomas Vondra @ 2022-08-30 00:22 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; David Rowley <dgrowleyml@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>



On 8/29/22 23:57, Tom Lane wrote:
> David Rowley <dgrowleyml@gmail.com> writes:
>> I've read over the emails and glanced at Tomas' patch. I think that
>> seems good. I think I'd rather see us do that than pad the struct out
>> further as Tomas' method is more aligned to what we do in aset.c
>> (ALLOC_BLOCKHDRSZ) and generation.c (Generation_BLOCKHDRSZ).
> 
>> I can adjust Tomas' patch to #define Slab_BLOCKHDRSZ
> 
> WFM
> 

Same here.

I also suggested doing a similar check in MemoryChunkGetPointer, so that
we catch the issue earlier - right after we allocate the chunk. Any
opinion on that? With an assert only in GetMemoryChunkMethodID() we'd
notice the issue much later, when it may not be obvious if it's a memory
corruption or what. But maybe it's overkill.

regards

-- 
Tomas Vondra
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 00:45  David Rowley <dgrowleyml@gmail.com>
  parent: Tomas Vondra <tomas.vondra@enterprisedb.com>
  0 siblings, 2 replies; 152+ messages in thread

From: David Rowley @ 2022-08-30 00:45 UTC (permalink / raw)
  To: Tomas Vondra <tomas.vondra@enterprisedb.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 30 Aug 2022 at 03:39, Tomas Vondra
<tomas.vondra@enterprisedb.com> wrote:
> The attached patch seems to fix the issue for me - at least it seems
> like that. This probably will need to get backpatched, I guess. Maybe we
> should add an assert to MemoryChunkGetPointer to check alignment?

Hi Tomas,

I just wanted to check with you if you ran the full make check-world
with this patch?

I don't yet have a working ARM 32-bit environment to test, but on
trying it with x86 32-bit and adjusting MAXIMUM_ALIGNOF to 8, I'm
getting failures in test_decoding. Namely:

test twophase                     ... FAILED       51 ms
test twophase_stream              ... FAILED       25 ms

 INSERT INTO test_prepared2 VALUES (5);
 SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL,
NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
+WARNING:  problem in slab Change: detected write past chunk end in
block 0x58b8ecf0, chunk 0x58b8ed08
+WARNING:  problem in slab Change: detected write past chunk end in
block 0x58b8ecf0, chunk 0x58b8ed58
+WARNING:  problem in slab Change: detected write past chunk end in
block 0x58b8ecf0, chunk 0x58b8eda8
+WARNING:  problem in slab Change: detected write past chunk end in
block 0x58b8ecf0, chunk 0x58b8edf8
+WARNING:  problem in slab Change: detected write past chunk end in
block 0x58b8ecf0, chunk 0x58b8ee48

I think the existing sentinel check looks wrong:

if (!sentinel_ok(chunk, slab->chunkSize))

shouldn't that be passing the pointer rather than the chunk?

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 01:04  David Rowley <dgrowleyml@gmail.com>
  parent: Tomas Vondra <tomas.vondra@enterprisedb.com>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-08-30 01:04 UTC (permalink / raw)
  To: Tomas Vondra <tomas.vondra@enterprisedb.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 30 Aug 2022 at 12:22, Tomas Vondra
<tomas.vondra@enterprisedb.com> wrote:
> I also suggested doing a similar check in MemoryChunkGetPointer, so that
> we catch the issue earlier - right after we allocate the chunk. Any
> opinion on that?

I think it's probably a good idea. However, I'm not yet sure if we can
keep it as a macro or if it would need to become a static inline
function to do that.

What I'd really have wished for is a macro like AssertPointersEqual()
that spat out the two pointer values. That would probably have saved
more time on this issue.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 01:16  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 3 replies; 152+ messages in thread

From: David Rowley @ 2022-08-30 01:16 UTC (permalink / raw)
  To: Tomas Vondra <tomas.vondra@enterprisedb.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 30 Aug 2022 at 12:45, David Rowley <dgrowleyml@gmail.com> wrote:
> I think the existing sentinel check looks wrong:
>
> if (!sentinel_ok(chunk, slab->chunkSize))
>
> shouldn't that be passing the pointer rather than the chunk?

Here's v2 of the slab-fix patch.

I've included the sentinel check fix.  This passes make check-world
for me when do a 32-bit build on my x86_64 machine and adjust
pg_config.h to set MAXIMUM_ALIGNOF to 8.

Any chance you could run make check-world on your 32-bit Raspberry PI?

I'm also wondering if this should also be backpatched back to v10,
providing the build farm likes it well enough on master.

Attachments:

slab-fix_v2.patch (text/plain, 2.3K) download diff --git a/src/backend/utils/mmgr/slab.c b/src/backend/utils/mmgr/slab.c index ae1a735b8c..02f365ff80 100644 --- a/src/backend/utils/mmgr/slab.c +++ b/src/backend/utils/mmgr/slab.c @@ -58,6 +58,8 @@ #include "utils/memutils_memorychunk.h" #include "utils/memutils_internal.h" +#define Slab_BLOCKHDRSZ MAXALIGN(sizeof(SlabBlock)) + /* * SlabContext is a specialized implementation of MemoryContext. */ @@ -102,10 +104,10 @@ typedef struct SlabBlock #define SlabChunkGetPointer(chk) \ ((void *)(((char *)(chk)) + sizeof(MemoryChunk))) #define SlabBlockGetChunk(slab, block, idx) \ - ((MemoryChunk *) ((char *) (block) + sizeof(SlabBlock) \ + ((MemoryChunk *) ((char *) (block) + Slab_BLOCKHDRSZ \ + (idx * slab->fullChunkSize))) #define SlabBlockStart(block) \ - ((char *) block + sizeof(SlabBlock)) + ((char *) block + Slab_BLOCKHDRSZ) #define SlabChunkIndex(slab, block, chunk) \ (((char *) chunk - SlabBlockStart(block)) / slab->fullChunkSize) @@ -146,12 +148,12 @@ SlabContextCreate(MemoryContext parent, fullChunkSize = Slab_CHUNKHDRSZ + MAXALIGN(chunkSize); /* Make sure the block can store at least one chunk. */ - if (blockSize < fullChunkSize + sizeof(SlabBlock)) + if (blockSize < fullChunkSize + Slab_BLOCKHDRSZ) elog(ERROR, "block size %zu for slab is too small for %zu chunks", blockSize, chunkSize); /* Compute maximum number of chunks per block */ - chunksPerBlock = (blockSize - sizeof(SlabBlock)) / fullChunkSize; + chunksPerBlock = (blockSize - Slab_BLOCKHDRSZ) / fullChunkSize; /* The freelist starts with 0, ends with chunksPerBlock. */ freelistSize = sizeof(dlist_head) * (chunksPerBlock + 1); @@ -733,6 +735,7 @@ SlabCheck(MemoryContext context) { MemoryChunk *chunk = SlabBlockGetChunk(slab, block, j); SlabBlock *chunkblock = (SlabBlock *) MemoryChunkGetBlock(chunk); + void *pointer = MemoryChunkGetPointer(chunk); /* * check the chunk's blockoffset correctly points back to @@ -744,7 +747,7 @@ SlabCheck(MemoryContext context) /* there might be sentinel (thanks to alignment) */ if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) - if (!sentinel_ok(chunk, slab->chunkSize)) + if (!sentinel_ok(pointer, slab->chunkSize)) elog(WARNING, "problem in slab %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); }
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 01:24  Tomas Vondra <tomas.vondra@enterprisedb.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 1 reply; 152+ messages in thread

From: Tomas Vondra @ 2022-08-30 01:24 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>



On 8/30/22 02:45, David Rowley wrote:
> On Tue, 30 Aug 2022 at 03:39, Tomas Vondra
> <tomas.vondra@enterprisedb.com> wrote:
>> The attached patch seems to fix the issue for me - at least it seems
>> like that. This probably will need to get backpatched, I guess. Maybe we
>> should add an assert to MemoryChunkGetPointer to check alignment?
> 
> Hi Tomas,
> 
> I just wanted to check with you if you ran the full make check-world
> with this patch?
> 
> I don't yet have a working ARM 32-bit environment to test, but on
> trying it with x86 32-bit and adjusting MAXIMUM_ALIGNOF to 8, I'm
> getting failures in test_decoding. Namely:
> 
> test twophase                     ... FAILED       51 ms
> test twophase_stream              ... FAILED       25 ms
> 
>  INSERT INTO test_prepared2 VALUES (5);
>  SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL,
> NULL, 'include-xids', '0', 'skip-empty-xacts', '1');
> +WARNING:  problem in slab Change: detected write past chunk end in
> block 0x58b8ecf0, chunk 0x58b8ed08
> +WARNING:  problem in slab Change: detected write past chunk end in
> block 0x58b8ecf0, chunk 0x58b8ed58
> +WARNING:  problem in slab Change: detected write past chunk end in
> block 0x58b8ecf0, chunk 0x58b8eda8
> +WARNING:  problem in slab Change: detected write past chunk end in
> block 0x58b8ecf0, chunk 0x58b8edf8
> +WARNING:  problem in slab Change: detected write past chunk end in
> block 0x58b8ecf0, chunk 0x58b8ee48
> 
> I think the existing sentinel check looks wrong:
> 
> if (!sentinel_ok(chunk, slab->chunkSize))
> 
> shouldn't that be passing the pointer rather than the chunk?
> 

I agree the check in SlabCheck() looks wrong, as it's ignoring the chunk
header (unlike the other contexts).

But yeah, I ran "make check-world" and it passed just fine, so my only
explanation is that the check never actually executes because there's no
space for the sentinel thanks to alignment, and the tweak you did breaks
that. Strange ...


regards

-- 
Tomas Vondra
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 01:45  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  2 siblings, 0 replies; 152+ messages in thread

From: Tom Lane @ 2022-08-30 01:45 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> Here's v2 of the slab-fix patch.

> I've included the sentinel check fix.  This passes make check-world
> for me when do a 32-bit build on my x86_64 machine and adjust
> pg_config.h to set MAXIMUM_ALIGNOF to 8.

> Any chance you could run make check-world on your 32-bit Raspberry PI?

I have clean core and test_decoding passes on both 32-bit ARM and
32-bit PPC.  It'll take awhile (couple hours) to finish a full
check-world, but I'd say that's good enough evidence to commit.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 01:55  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Tomas Vondra <tomas.vondra@enterprisedb.com>
  0 siblings, 2 replies; 152+ messages in thread

From: Tom Lane @ 2022-08-30 01:55 UTC (permalink / raw)
  To: Tomas Vondra <tomas.vondra@enterprisedb.com>; +Cc: David Rowley <dgrowleyml@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Tomas Vondra <tomas.vondra@enterprisedb.com> writes:
> On 8/30/22 02:45, David Rowley wrote:
>> I think the existing sentinel check looks wrong:
>> if (!sentinel_ok(chunk, slab->chunkSize))
>> shouldn't that be passing the pointer rather than the chunk?

> I agree the check in SlabCheck() looks wrong, as it's ignoring the chunk
> header (unlike the other contexts).

> But yeah, I ran "make check-world" and it passed just fine, so my only
> explanation is that the check never actually executes because there's no
> space for the sentinel thanks to alignment, and the tweak you did breaks
> that. Strange ...

A quick code-coverage check confirms that the sentinel_ok() line
is not reached in core or test_decoding tests as of HEAD
(on a 64-bit machine anyway).  So we just happen to be using
only allocation requests that are already maxaligned.

I wonder if slab ought to artificially bump up such requests when
MEMORY_CONTEXT_CHECKING is enabled, so there's room for a sentinel.
I think it's okay for aset.c to not do that, because its power-of-2
behavior means there usually is room for a sentinel; but slab's
policy makes it much more likely that there won't be.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 01:58  Tomas Vondra <tomas.vondra@enterprisedb.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  2 siblings, 2 replies; 152+ messages in thread

From: Tomas Vondra @ 2022-08-30 01:58 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On 8/30/22 03:16, David Rowley wrote:
> On Tue, 30 Aug 2022 at 12:45, David Rowley <dgrowleyml@gmail.com> wrote:
>> I think the existing sentinel check looks wrong:
>>
>> if (!sentinel_ok(chunk, slab->chunkSize))
>>
>> shouldn't that be passing the pointer rather than the chunk?
> 
> Here's v2 of the slab-fix patch.
> 
> I've included the sentinel check fix.  This passes make check-world
> for me when do a 32-bit build on my x86_64 machine and adjust
> pg_config.h to set MAXIMUM_ALIGNOF to 8.
> 
> Any chance you could run make check-world on your 32-bit Raspberry PI?
> 

Will do, but I think the sentinel fix should be

   if (!sentinel_ok(chunk, Slab_CHUNKHDRSZ + slab->chunkSize))

which is what the other contexts do. However, considering check-world
passed even before the sentinel_ok fix, I'm a bit skeptical about that
proving anything.

FWIW I added a WARNING to SlabCheck before the condition guarding the
sentinel check, printing the (full) chunk size and header size, and this
is what I got in test_decoding (deduplicated):

armv7l (32-bit rpi4)

+WARNING:  chunkSize 216 fullChunkSize 232 header 16
+WARNING:  chunkSize 64 fullChunkSize 80 header 16

aarch64 (64-bit rpi4)

+WARNING:  chunkSize 304 fullChunkSize 320 header 16
+WARNING:  chunkSize 80 fullChunkSize 96 header 16

So indeed, those are *perfect* matches and thus the sentinel_ok() never
executed. So no failures until now. On x86-64 I get the same thing as on
aarch64. I guess that explains why it never failed. Seems like a pretty
amazing coincidence ...


> I'm also wondering if this should also be backpatched back to v10,
> providing the build farm likes it well enough on master.

I'd say the sentinel fix may need to be backpatched.


regard

-- 
Tomas Vondra
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 02:12  Tomas Vondra <tomas.vondra@enterprisedb.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 0 replies; 152+ messages in thread

From: Tomas Vondra @ 2022-08-30 02:12 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: David Rowley <dgrowleyml@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On 8/30/22 03:55, Tom Lane wrote:
> Tomas Vondra <tomas.vondra@enterprisedb.com> writes:
>> On 8/30/22 02:45, David Rowley wrote:
>>> I think the existing sentinel check looks wrong:
>>> if (!sentinel_ok(chunk, slab->chunkSize))
>>> shouldn't that be passing the pointer rather than the chunk?
> 
>> I agree the check in SlabCheck() looks wrong, as it's ignoring the chunk
>> header (unlike the other contexts).
> 
>> But yeah, I ran "make check-world" and it passed just fine, so my only
>> explanation is that the check never actually executes because there's no
>> space for the sentinel thanks to alignment, and the tweak you did breaks
>> that. Strange ...
> 
> A quick code-coverage check confirms that the sentinel_ok() line
> is not reached in core or test_decoding tests as of HEAD
> (on a 64-bit machine anyway).  So we just happen to be using
> only allocation requests that are already maxaligned.
> 
> I wonder if slab ought to artificially bump up such requests when
> MEMORY_CONTEXT_CHECKING is enabled, so there's room for a sentinel.
> I think it's okay for aset.c to not do that, because its power-of-2
> behavior means there usually is room for a sentinel; but slab's
> policy makes it much more likely that there won't be.
> 

+1 to that

For aset that's fine not just because of power-of-2 behavior, but
because we use it for chunks of many different sizes - so at least some
of those will have sentinel.

But Slab in used only for changes and txns in reorderbuffer, and it just
so happens both structs are maxaligned on 32-bit and 64-bit machines
(rpi and x86-64). We're unlikely to use slab in many other places, and
the structs don't change very often, and it'd probably grow to another
maxaligned size anyway. So it may be pretty rare to have a sentinel.



regards

-- 
Tomas Vondra
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 02:29  David Rowley <dgrowleyml@gmail.com>
  parent: Tomas Vondra <tomas.vondra@enterprisedb.com>
  1 sibling, 0 replies; 152+ messages in thread

From: David Rowley @ 2022-08-30 02:29 UTC (permalink / raw)
  To: Tomas Vondra <tomas.vondra@enterprisedb.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 30 Aug 2022 at 13:58, Tomas Vondra
<tomas.vondra@enterprisedb.com> wrote:
> armv7l (32-bit rpi4)
>
> +WARNING:  chunkSize 216 fullChunkSize 232 header 16
> +WARNING:  chunkSize 64 fullChunkSize 80 header 16
>
> aarch64 (64-bit rpi4)
>
> +WARNING:  chunkSize 304 fullChunkSize 320 header 16
> +WARNING:  chunkSize 80 fullChunkSize 96 header 16
>
> So indeed, those are *perfect* matches and thus the sentinel_ok() never
> executed. So no failures until now. On x86-64 I get the same thing as on
> aarch64. I guess that explains why it never failed. Seems like a pretty
> amazing coincidence ...

hmm, I'm not so sure I agree that it's an amazing coincidence. Isn't
it quite likely that the chunksize being given to SlabContextCreate()
is the same as MAXALIGN(chunksize)? Isn't that all it would take?

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 02:31  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 2 replies; 152+ messages in thread

From: David Rowley @ 2022-08-30 02:31 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 30 Aug 2022 at 13:55, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> I wonder if slab ought to artificially bump up such requests when
> MEMORY_CONTEXT_CHECKING is enabled, so there's room for a sentinel.
> I think it's okay for aset.c to not do that, because its power-of-2
> behavior means there usually is room for a sentinel; but slab's
> policy makes it much more likely that there won't be.

I think it's fairly likely that small allocations are a power of 2,
and I think most of our allocates are small, so I imagine that if we
didn't do that for aset.c, we'd miss out on most of the benefits.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 02:42  David Rowley <dgrowleyml@gmail.com>
  parent: Tomas Vondra <tomas.vondra@enterprisedb.com>
  1 sibling, 0 replies; 152+ messages in thread

From: David Rowley @ 2022-08-30 02:42 UTC (permalink / raw)
  To: Tomas Vondra <tomas.vondra@enterprisedb.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 30 Aug 2022 at 13:58, Tomas Vondra
<tomas.vondra@enterprisedb.com> wrote:
>
> On 8/30/22 03:16, David Rowley wrote:
> > Any chance you could run make check-world on your 32-bit Raspberry PI?
> >
>
> Will do, but I think the sentinel fix should be

Thank you.  I think Tom is also running make check-world.  I now have
an old RPI3 setup with a 32-bit OS, which is currently busy compiling
Postgres. I'll kick off a make check-world run once that's done.

>    if (!sentinel_ok(chunk, Slab_CHUNKHDRSZ + slab->chunkSize))

Agreed. I've changed the patch to do it that way.  Since the 32-bit
ARM animals are already broken and per what Tom mentioned in [1], I've
pushed the patch.

Thanks again for taking the time to look at this.

David

[1] https://www.postgresql.org/message-id/3455754.1661823905@sss.pgh.pa.us





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 03:01  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-08-30 03:01 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 30 Aug 2022 at 03:39, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> I'd suggest reverting df0f4feef as it seems to be
> a red herring.

I think it's useless providing that a 64-bit variable will always be
aligned to 8 bytes on all of our supported 32-bit platforms as,
without the padding, the uint64 hdrmask in MemoryChunk will always be
aligned to 8 bytes meaning the memory following that will be aligned
too.  If we have a platform where a uint64 isn't aligned to 8 bytes
then we might need the padding.

long long seems to align to 8 bytes on my 32-bit Rasberry PI going the
struct being 16 bytes rather than 12.

drowley@raspberrypi:~ $ cat struct.c
#include <stdio.h>

typedef struct test
{
        int a;
        long long b;
} test;

int main(void)
{
        printf("%d\n", sizeof(test));
        return 0;
}
drowley@raspberrypi:~ $ gcc struct.c -o struct
drowley@raspberrypi:~ $ ./struct
16
drowley@raspberrypi:~ $ uname -m
armv7l

Is that the case for your 32-bit PPC too?

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 03:15  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-08-30 03:15 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> On Tue, 30 Aug 2022 at 03:39, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> I'd suggest reverting df0f4feef as it seems to be
>> a red herring.

> I think it's useless providing that a 64-bit variable will always be
> aligned to 8 bytes on all of our supported 32-bit platforms as,
> without the padding, the uint64 hdrmask in MemoryChunk will always be
> aligned to 8 bytes meaning the memory following that will be aligned
> too.  If we have a platform where a uint64 isn't aligned to 8 bytes
> then we might need the padding.

It's not so much "8 bytes".  The question is this: is there any
platform on which uint64 has less than MAXALIGN alignment
requirement?  If it is maxaligned then the compiler will insert any
required padding automatically, so the patch accomplishes little.

AFAICS that could only happen if "double" has 8-byte alignment
requirement but int64 does not.  I recall some discussion about
that possibility a month or two back, but I think we concluded
that we weren't going to support it.

I guess what I mostly don't like about df0f4feef is the hardwired "8"
constants.  Yeah, it's hard to see how sizeof(uint64) isn't 8, but
it's not very readable like this IMO.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 03:21  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-08-30 03:21 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 30 Aug 2022 at 15:15, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> AFAICS that could only happen if "double" has 8-byte alignment
> requirement but int64 does not.  I recall some discussion about
> that possibility a month or two back, but I think we concluded
> that we weren't going to support it.

ok

> I guess what I mostly don't like about df0f4feef is the hardwired "8"
> constants.  Yeah, it's hard to see how sizeof(uint64) isn't 8, but
> it's not very readable like this IMO.

Yeah, that was just down to lack of any SIZEOF_* macro to tell me
uint64 was 8 bytes.

I can revert df0f4feef, but would prefer just to get the green light
for d5ee4db0e from those 32-bit arm animals before doing so.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 03:31  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 0 replies; 152+ messages in thread

From: Tom Lane @ 2022-08-30 03:31 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> I can revert df0f4feef, but would prefer just to get the green light
> for d5ee4db0e from those 32-bit arm animals before doing so.

I have a check-world pass on my RPI3 (Fedora 30 armv7l image).
PPC test still running, but I don't doubt it will pass; it's
finished contrib/test_decoding.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 07:14  David Rowley <dgrowleyml@gmail.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  1 sibling, 2 replies; 152+ messages in thread

From: David Rowley @ 2022-08-30 07:14 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 30 Aug 2022 at 03:16, Robert Haas <robertmhaas@gmail.com> wrote:
> ../../../../src/include/utils/memutils_memorychunk.h:186:18: error:
> comparison of constant 7 with expression of type
> 'MemoryContextMethodID' (aka 'enum MemoryContextMethodID') is always
> true [-Werror,-Wtautological-constant-out-of-range-compare]
>         Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK);
>         ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> ../../../../src/include/c.h:827:9: note: expanded from macro 'Assert'
>                 if (!(condition)) \
>                       ^~~~~~~~~
>
> I'm not sure what to do about that, but every file that includes
> memutils_memorychunk.h produces those warnings (which become errors
> due to -Werror).

I'm not really sure either. I tried compiling with clang 12.0.1 with
-Wtautological-constant-out-of-range-compare and don't get this
warning.

I think the Assert is useful as if we were ever to add an enum member
with the value of 8 and forgot to adjust MEMORY_CONTEXT_METHODID_BITS
then bad things would happen inside MemoryChunkSetHdrMask() and
MemoryChunkSetHdrMaskExternal().  I think it's unlikely we'll ever get
that many MemoryContext types, but I don't know for sure and would
rather the person who adds the 9th one get alerted to the lack of bit
space in MemoryChunk as soon as possible.

As much as I'm not a fan of adding new warnings for compiler options
that are not part of our standard set, I feel like if there are
warning flags out there that are as giving us false warnings such as
this one, then we shouldn't trouble ourselves trying to get rid of
them, especially so when they force us to remove something which might
catch a future bug.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 08:33  Tomas Vondra <tomas.vondra@enterprisedb.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 0 replies; 152+ messages in thread

From: Tomas Vondra @ 2022-08-30 08:33 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>



On 8/30/22 03:04, David Rowley wrote:
> On Tue, 30 Aug 2022 at 12:22, Tomas Vondra
> <tomas.vondra@enterprisedb.com> wrote:
>> I also suggested doing a similar check in MemoryChunkGetPointer, so that
>> we catch the issue earlier - right after we allocate the chunk. Any
>> opinion on that?
> 
> I think it's probably a good idea. However, I'm not yet sure if we can
> keep it as a macro or if it would need to become a static inline
> function to do that.
> 

I'd bet it can be done in the macro. See VARATT_EXTERNAL_GET_POINTER for
example of a "do" block with an Assert.

> What I'd really have wished for is a macro like AssertPointersEqual()
> that spat out the two pointer values. That would probably have saved
> more time on this issue.
> 

Hmm, maybe.

regards

-- 
Tomas Vondra
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 09:05  Tomas Vondra <tomas.vondra@enterprisedb.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 0 replies; 152+ messages in thread

From: Tomas Vondra @ 2022-08-30 09:05 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>



On 8/30/22 04:31, David Rowley wrote:
> On Tue, 30 Aug 2022 at 13:55, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> I wonder if slab ought to artificially bump up such requests when
>> MEMORY_CONTEXT_CHECKING is enabled, so there's room for a sentinel.
>> I think it's okay for aset.c to not do that, because its power-of-2
>> behavior means there usually is room for a sentinel; but slab's
>> policy makes it much more likely that there won't be.
> 
> I think it's fairly likely that small allocations are a power of 2,
> and I think most of our allocates are small, so I imagine that if we
> didn't do that for aset.c, we'd miss out on most of the benefits.
> 

Yeah. I think we have a fair number of "larger" allocations (once you
get to ~100B it probably won't be a 2^N), but we may easily miss whole
sections of allocations.

I guess the idea was to add a sentinel only when there already is space
for it, but perhaps that's a bad tradeoff limiting the benefits. Either
we add the sentinel fairly often (and then why not just add it all the
time - it'll need a bit more space), or we do it only very rarely (and
then it's a matter of luck if it catches an issue). Considering we only
do this with asserts, I doubt the extra bytes / CPU is a major issue,
and a (more) reliable detection of issues seems worth it. But maybe I
underestimate the costs. The only alternative seems to be valgrind, and
that's way costlier, though.

regards

-- 
Tomas Vondra
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 13:26  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-08-30 13:26 UTC (permalink / raw)
  To: Tomas Vondra <tomas.vondra@enterprisedb.com>; +Cc: David Rowley <dgrowleyml@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Tomas Vondra <tomas.vondra@enterprisedb.com> writes:
> I guess the idea was to add a sentinel only when there already is space
> for it, but perhaps that's a bad tradeoff limiting the benefits. Either
> we add the sentinel fairly often (and then why not just add it all the
> time - it'll need a bit more space), or we do it only very rarely (and
> then it's a matter of luck if it catches an issue).

I'm fairly sure that when we made that decision originally, a top-of-mind
case was ListCells, which are plentiful, small, power-of-2-sized, and
not used in a way likely to have buffer overruns.  But since the List
rewrite a couple years back we no longer palloc individual ListCells.
So maybe we should revisit the question.  It'd be worth collecting some
stats about how much extra space would be needed if we force there
to be room for a sentinel.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 13:36  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-08-30 13:36 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> On Tue, 30 Aug 2022 at 03:16, Robert Haas <robertmhaas@gmail.com> wrote:
>> ../../../../src/include/utils/memutils_memorychunk.h:186:18: error:
>> comparison of constant 7 with expression of type
>> 'MemoryContextMethodID' (aka 'enum MemoryContextMethodID') is always
>> true [-Werror,-Wtautological-constant-out-of-range-compare]
>> Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK);
>> ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

> I think the Assert is useful as if we were ever to add an enum member
> with the value of 8 and forgot to adjust MEMORY_CONTEXT_METHODID_BITS
> then bad things would happen inside MemoryChunkSetHdrMask() and
> MemoryChunkSetHdrMaskExternal().  I think it's unlikely we'll ever get
> that many MemoryContext types, but I don't know for sure and would
> rather the person who adds the 9th one get alerted to the lack of bit
> space in MemoryChunk as soon as possible.

I think that's a weak argument, so I don't mind dropping this Assert.
What would be far more useful is a comment inside the
MemoryContextMethodID enum pointing out that we can support at most
8 values because XYZ.

However, I'm still wondering why Robert sees this when the rest of us
don't.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 14:17  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-08-30 14:17 UTC (permalink / raw)
  To: Tomas Vondra <tomas.vondra@enterprisedb.com>; +Cc: David Rowley <dgrowleyml@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

I wrote:
> So maybe we should revisit the question.  It'd be worth collecting some
> stats about how much extra space would be needed if we force there
> to be room for a sentinel.

Actually, after ingesting more caffeine, the problem with this for aset.c
is that the only way to add space for a sentinel that didn't fit already
is to double the space allocation.  That's a little daunting, especially
remembering how many places deliberately allocate power-of-2-sized
arrays.

You could imagine deciding that the space classifications are not
power-of-2 but power-of-2-plus-one, or something like that.  But that
would be very invasive to the logic, and I doubt it's a good idea.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 15:00  Robert Haas <robertmhaas@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 1 reply; 152+ messages in thread

From: Robert Haas @ 2022-08-30 15:00 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, Aug 30, 2022 at 3:14 AM David Rowley <dgrowleyml@gmail.com> wrote:
> I'm not really sure either. I tried compiling with clang 12.0.1 with
> -Wtautological-constant-out-of-range-compare and don't get this
> warning.

I have a much older clang version, it seems. clang -v reports 5.0.2. I
use -Wall and -Werror as a matter of habit. It looks like 5.0.2 was
released in May 2018, installed by me in November of 2019, and I just
haven't had a reason to upgrade.

> I think the Assert is useful as if we were ever to add an enum member
> with the value of 8 and forgot to adjust MEMORY_CONTEXT_METHODID_BITS
> then bad things would happen inside MemoryChunkSetHdrMask() and
> MemoryChunkSetHdrMaskExternal().  I think it's unlikely we'll ever get
> that many MemoryContext types, but I don't know for sure and would
> rather the person who adds the 9th one get alerted to the lack of bit
> space in MemoryChunk as soon as possible.

Well I don't have a problem with that, but I think we should try to do
it without causing compiler warnings. The attached patch fixes it for
me.

> As much as I'm not a fan of adding new warnings for compiler options
> that are not part of our standard set, I feel like if there are
> warning flags out there that are as giving us false warnings such as
> this one, then we shouldn't trouble ourselves trying to get rid of
> them, especially so when they force us to remove something which might
> catch a future bug.

For me the point is that, at least on the compiler that I'm using, the
warning suggests that the compiler will optimize the test away
completely, and therefore it wouldn't catch a future bug. Could there
be compilers where no warning is generated but the assertion is still
optimized away?

I don't know, but I don't think a 4-year-old compiler is such a fossil
that we shouldn't care whether it produces warnings. We worry about
operating systems and PostgreSQL versions that are almost extinct in
the wild, so saying we're not going to worry about failing to update
the compiler regularly enough within the lifetime of one off-the-shelf
MacBook does not really make sense to me.

-- 
Robert Haas
EDB: http://www.enterprisedb.com

Attachments:

fix-memorychunk-warnings.patch (application/octet-stream, 1.0K) download diff --git a/src/include/utils/memutils_memorychunk.h b/src/include/utils/memutils_memorychunk.h index 1e27d084cd..2c3dbb27e3 100644 --- a/src/include/utils/memutils_memorychunk.h +++ b/src/include/utils/memutils_memorychunk.h @@ -167,7 +167,7 @@ MemoryChunkSetHdrMask(MemoryChunk *chunk, void *block, Assert((char *) chunk > (char *) block); Assert(blockoffset <= MEMORYCHUNK_MAX_BLOCKOFFSET); Assert(value <= MEMORYCHUNK_MAX_VALUE); - Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK); + Assert((int) methodid <= MEMORY_CONTEXT_METHODID_MASK); chunk->hdrmask = (((uint64) blockoffset) << MEMORYCHUNK_BLOCKOFFSET_BASEBIT) | (((uint64) value) << MEMORYCHUNK_VALUE_BASEBIT) | @@ -183,7 +183,7 @@ static inline void MemoryChunkSetHdrMaskExternal(MemoryChunk *chunk, MemoryContextMethodID methodid) { - Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK); + Assert((int) methodid <= MEMORY_CONTEXT_METHODID_MASK); chunk->hdrmask = MEMORYCHUNK_MAGIC | (((uint64) 1) << MEMORYCHUNK_EXTERNAL_BASEBIT) | methodid;
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 15:25  David Rowley <dgrowleyml@gmail.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 0 replies; 152+ messages in thread

From: David Rowley @ 2022-08-30 15:25 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Wed, 31 Aug 2022 at 03:00, Robert Haas <robertmhaas@gmail.com> wrote:
>
> On Tue, Aug 30, 2022 at 3:14 AM David Rowley <dgrowleyml@gmail.com> wrote:
> > I think the Assert is useful as if we were ever to add an enum member
> > with the value of 8 and forgot to adjust MEMORY_CONTEXT_METHODID_BITS
> > then bad things would happen inside MemoryChunkSetHdrMask() and
> > MemoryChunkSetHdrMaskExternal().  I think it's unlikely we'll ever get
> > that many MemoryContext types, but I don't know for sure and would
> > rather the person who adds the 9th one get alerted to the lack of bit
> > space in MemoryChunk as soon as possible.
>
> Well I don't have a problem with that, but I think we should try to do
> it without causing compiler warnings. The attached patch fixes it for
> me.

I'm fine with adding the int cast. Seems like a good idea.

> > As much as I'm not a fan of adding new warnings for compiler options
> > that are not part of our standard set, I feel like if there are
> > warning flags out there that are as giving us false warnings such as
> > this one, then we shouldn't trouble ourselves trying to get rid of
> > them, especially so when they force us to remove something which might
> > catch a future bug.
>
> For me the point is that, at least on the compiler that I'm using, the
> warning suggests that the compiler will optimize the test away
> completely, and therefore it wouldn't catch a future bug. Could there
> be compilers where no warning is generated but the assertion is still
> optimized away?

I'd not considered that the compiler might optimise it away.  My
suspicions had been more along the lines of that clang removed the
enum out of range warnings because they were annoying and wrong as
it's pretty easy to set an enum variable to something out of range of
the defined enum values.

Looking at [1], it seems like 5.0.2 is producing the correct code and
it's just producing a warning. The 2nd compiler window has -Werror and
shows that it does fail to compile. If I change that to use clang
6.0.0 then it works. It seems to fail all the way back to clang 3.1.
clang 3.0.0 works.

David

[1] https://godbolt.org/z/Gx388z5Ej





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 15:31  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-08-30 15:31 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Robert Haas <robertmhaas@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Wed, 31 Aug 2022 at 01:36, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> David Rowley <dgrowleyml@gmail.com> writes:
> > I think the Assert is useful as if we were ever to add an enum member
> > with the value of 8 and forgot to adjust MEMORY_CONTEXT_METHODID_BITS
> > then bad things would happen inside MemoryChunkSetHdrMask() and
> > MemoryChunkSetHdrMaskExternal().  I think it's unlikely we'll ever get
> > that many MemoryContext types, but I don't know for sure and would
> > rather the person who adds the 9th one get alerted to the lack of bit
> > space in MemoryChunk as soon as possible.
>
> I think that's a weak argument, so I don't mind dropping this Assert.
> What would be far more useful is a comment inside the
> MemoryContextMethodID enum pointing out that we can support at most
> 8 values because XYZ.

I'd just sleep better knowing that we have some test coverage to
ensure that MemoryChunkSetHdrMask() and
MemoryChunkSetHdrMaskExternal() have some verification that we don't
end up with future code that will cause the hdrmask to be invalid.  I
tried to make those functions as lightweight as possible. Without the
Assert, I just feel that there's a bit too much trust that none of the
bits overlap.  I've no objections to adding a comment to the enum to
explain to future devs. My vote would be for that and add the (int)
cast as proposed by Robert.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 15:39  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 2 replies; 152+ messages in thread

From: David Rowley @ 2022-08-30 15:39 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Robert Haas <robertmhaas@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Wed, 31 Aug 2022 at 03:31, David Rowley <dgrowleyml@gmail.com> wrote:
> I've no objections to adding a comment to the enum to
> explain to future devs. My vote would be for that and add the (int)
> cast as proposed by Robert.

Here's a patch which adds a comment to MemoryContextMethodID to Robert's patch.

David

Attachments:

fix-memorychunk-warnings_v2.patch (text/plain, 1.7K) download diff --git a/src/include/utils/memutils_internal.h b/src/include/utils/memutils_internal.h index 9a9f52ef16..f348282a07 100644 --- a/src/include/utils/memutils_internal.h +++ b/src/include/utils/memutils_internal.h @@ -74,6 +74,9 @@ extern void SlabCheck(MemoryContext context); * MemoryContextMethodID * A unique identifier for each MemoryContext implementation which * indicates the index into the mcxt_methods[] array. See mcxt.c. + * The maximum value for this enum is constrained by + * MEMORY_CONTEXT_METHODID_MASK. If an enum value higher than that is + * required then MEMORY_CONTEXT_METHODID_BITS will need to be increased. */ typedef enum MemoryContextMethodID { diff --git a/src/include/utils/memutils_memorychunk.h b/src/include/utils/memutils_memorychunk.h index 685c177b68..2eefc138e3 100644 --- a/src/include/utils/memutils_memorychunk.h +++ b/src/include/utils/memutils_memorychunk.h @@ -159,7 +159,7 @@ MemoryChunkSetHdrMask(MemoryChunk *chunk, void *block, Assert((char *) chunk > (char *) block); Assert(blockoffset <= MEMORYCHUNK_MAX_BLOCKOFFSET); Assert(value <= MEMORYCHUNK_MAX_VALUE); - Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK); + Assert((int) methodid <= MEMORY_CONTEXT_METHODID_MASK); chunk->hdrmask = (((uint64) blockoffset) << MEMORYCHUNK_BLOCKOFFSET_BASEBIT) | (((uint64) value) << MEMORYCHUNK_VALUE_BASEBIT) | @@ -175,7 +175,7 @@ static inline void MemoryChunkSetHdrMaskExternal(MemoryChunk *chunk, MemoryContextMethodID methodid) { - Assert(methodid <= MEMORY_CONTEXT_METHODID_MASK); + Assert((int) methodid <= MEMORY_CONTEXT_METHODID_MASK); chunk->hdrmask = MEMORYCHUNK_MAGIC | (((uint64) 1) << MEMORYCHUNK_EXTERNAL_BASEBIT) | methodid;
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 15:54  Robert Haas <robertmhaas@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 0 replies; 152+ messages in thread

From: Robert Haas @ 2022-08-30 15:54 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, Aug 30, 2022 at 11:39 AM David Rowley <dgrowleyml@gmail.com> wrote:
> On Wed, 31 Aug 2022 at 03:31, David Rowley <dgrowleyml@gmail.com> wrote:
> > I've no objections to adding a comment to the enum to
> > explain to future devs. My vote would be for that and add the (int)
> > cast as proposed by Robert.
>
> Here's a patch which adds a comment to MemoryContextMethodID to Robert's patch.

LGTM.

-- 
Robert Haas
EDB: http://www.enterprisedb.com





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 16:17  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 0 replies; 152+ messages in thread

From: Tom Lane @ 2022-08-30 16:17 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> Here's a patch which adds a comment to MemoryContextMethodID to Robert's patch.

OK, but while looking at that I noticed the adjacent

#define MEMORY_CONTEXT_METHODID_MASK \
	UINT64CONST((1 << MEMORY_CONTEXT_METHODID_BITS) - 1)

I'm rather astonished that that compiles; UINT64CONST was only ever
meant to be applied to *literals*.  I think what it's expanding to
is

	((1 << MEMORY_CONTEXT_METHODID_BITS) - 1UL)

(or on some machines 1ULL) which only accidentally does approximately
what you want.  It'd be all right perhaps to write

	((UINT64CONST(1) << MEMORY_CONTEXT_METHODID_BITS) - 1)

but you might as well avoid the Postgres-ism and just write

	((uint64) ((1 << MEMORY_CONTEXT_METHODID_BITS) - 1))

Nobody's ever going to make MEMORY_CONTEXT_METHODID_BITS large
enough for the shift to overflow in int arithmetic.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-30 22:40  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-08-30 22:40 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Wed, 31 Aug 2022 at 02:17, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> I wrote:
> > So maybe we should revisit the question.  It'd be worth collecting some
> > stats about how much extra space would be needed if we force there
> > to be room for a sentinel.
>
> Actually, after ingesting more caffeine, the problem with this for aset.c
> is that the only way to add space for a sentinel that didn't fit already
> is to double the space allocation.  That's a little daunting, especially
> remembering how many places deliberately allocate power-of-2-sized
> arrays.

I decided to try and quantify that by logging the size, MAXALIGN(size)
and the power of 2 size during AllocSetAlloc and GenerationAlloc. I
made the pow2_size 0 in GenerationAlloc and in AlloocSetAlloc when
size > allocChunkLimit.

After running make installcheck, grabbing the records out the log and
loading them into Postgres, I see that if we did double the pow2_size
when there's no space for the sentinel byte then we'd go from
allocating a total of 10.2GB all the way to 16.4GB (!) of
non-dedicated block aset.c allocations.

select
round(sum(pow2_Size)::numeric/1024/1024/1024,3) as pow2_size,
round(sum(case when maxalign_size=pow2_size then pow2_size*2 else
pow2_size end)::numeric/1024/1024/1024,3) as method1,
round(sum(case when maxalign_size=pow2_size then pow2_size+8 else
pow2_size end)::numeric/1024/1024/1024,3) as method2
from memstats
where pow2_size > 0;
 pow2_size | method1 | method2
-----------+---------+---------
    10.194 |  16.382 |  10.463

if we did just add on an extra 8 bytes (or or MAXALIGN(size+1) at
least), then that would take the size up to 10.5GB.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-31 20:53  Tomas Vondra <tomas.vondra@enterprisedb.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: Tomas Vondra @ 2022-08-31 20:53 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>



On 8/31/22 00:40, David Rowley wrote:
> On Wed, 31 Aug 2022 at 02:17, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>>
>> I wrote:
>>> So maybe we should revisit the question.  It'd be worth collecting some
>>> stats about how much extra space would be needed if we force there
>>> to be room for a sentinel.
>>
>> Actually, after ingesting more caffeine, the problem with this for aset.c
>> is that the only way to add space for a sentinel that didn't fit already
>> is to double the space allocation.  That's a little daunting, especially
>> remembering how many places deliberately allocate power-of-2-sized
>> arrays.
> 
> I decided to try and quantify that by logging the size, MAXALIGN(size)
> and the power of 2 size during AllocSetAlloc and GenerationAlloc. I
> made the pow2_size 0 in GenerationAlloc and in AlloocSetAlloc when
> size > allocChunkLimit.
> 
> After running make installcheck, grabbing the records out the log and
> loading them into Postgres, I see that if we did double the pow2_size
> when there's no space for the sentinel byte then we'd go from
> allocating a total of 10.2GB all the way to 16.4GB (!) of
> non-dedicated block aset.c allocations.
> 
> select
> round(sum(pow2_Size)::numeric/1024/1024/1024,3) as pow2_size,
> round(sum(case when maxalign_size=pow2_size then pow2_size*2 else
> pow2_size end)::numeric/1024/1024/1024,3) as method1,
> round(sum(case when maxalign_size=pow2_size then pow2_size+8 else
> pow2_size end)::numeric/1024/1024/1024,3) as method2
> from memstats
> where pow2_size > 0;
>  pow2_size | method1 | method2
> -----------+---------+---------
>     10.194 |  16.382 |  10.463
> 
> if we did just add on an extra 8 bytes (or or MAXALIGN(size+1) at
> least), then that would take the size up to 10.5GB.
> 

I've been experimenting with this a bit too, and my results are similar,
but not exactly the same. I've logged all Alloc/Realloc calls for the
two memory contexts, and when I aggregated the results I get this:

        f        |     size | pow2(size) | pow2(size+1)
-----------------+----------+------------+--------------
 AllocSetAlloc   |    23528 |      28778 |        31504
 AllocSetRelloc  |      761 |        824 |         1421
 GenerationAlloc |       68 |         90 |          102

So the raw size (what we asked for) is ~23.5GB, but in practice we
allocate ~28.8GB because of the pow-of-2 logic. And by adding the extra
1B we end up allocating 31.5GB. That doesn't seem like a huge increase,
and it's far from the +60% you got.

I wonder where does the difference come - I did make installcheck too,
so how come you get 10/16GB, and I get 28/31GB? My patch is attached,
maybe I did something silly.

I also did a quick hack to see if always having the sentinel detects any
pre-existing issues, but that didn't happen. I guess valgrind would find
those, but not sure?


regards

-- 
Tomas Vondra
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

Attachments:

sentinel-tweak.patch (text/x-patch, 7.6K) download diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index b6eeb8abab..e6d86a54d7 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -674,6 +674,15 @@ AllocSetDelete(MemoryContext context) free(set); } +static Size pow2_size(Size size) +{ + Size s = 1; + while (s < size) + s *= 2; + + return s; +} + /* * AllocSetAlloc * Returns pointer to allocated memory of given size or NULL if @@ -699,13 +708,16 @@ AllocSetAlloc(MemoryContext context, Size size) AssertArg(AllocSetIsValid(set)); + fprintf(stderr, "AllocSetAlloc %ld %ld %ld\n", size, pow2_size(size), pow2_size(size+1)); + fflush(stderr); + /* * If requested size exceeds maximum for chunks, allocate an entire block * for this request. */ - if (size > set->allocChunkLimit) + if (size + 1 > set->allocChunkLimit) { - chunk_size = MAXALIGN(size); + chunk_size = MAXALIGN(size + 1); blksize = chunk_size + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ; block = (AllocBlock) malloc(blksize); if (block == NULL) @@ -725,7 +737,16 @@ AllocSetAlloc(MemoryContext context, Size size) chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk_size) + { set_sentinel(MemoryChunkGetPointer(chunk), size); + fprintf(stderr, "sentinel added\n"); + fflush(stderr); + } + else + { + fprintf(stderr, "A sentinel not added\n"); + fflush(stderr); + } #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ @@ -767,7 +788,7 @@ AllocSetAlloc(MemoryContext context, Size size) * If one is found, remove it from the free list, make it again a member * of the alloc set and return its data address. */ - fidx = AllocSetFreeIndex(size); + fidx = AllocSetFreeIndex(size+1); chunk = set->freelist[fidx]; if (chunk != NULL) { @@ -784,7 +805,16 @@ AllocSetAlloc(MemoryContext context, Size size) chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < GetChunkSizeFromFreeListIdx(fidx)) + { set_sentinel(MemoryChunkGetPointer(chunk), size); + fprintf(stderr, "sentinel added\n"); + fflush(stderr); + } + else + { + fprintf(stderr, "B sentinel not added\n"); + fflush(stderr); + } #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ @@ -950,7 +980,16 @@ AllocSetAlloc(MemoryContext context, Size size) chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk_size) + { set_sentinel(MemoryChunkGetPointer(chunk), size); + fprintf(stderr, "sentinel added\n"); + fflush(stderr); + } + else + { + fprintf(stderr, "C sentinel not added\n"); + fflush(stderr); + } #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ @@ -994,7 +1033,7 @@ AllocSetFree(void *pointer) /* Test for someone scribbling on unused space in chunk */ if (chunk->requested_size < chunk_size) if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", + elog(ERROR, "detected write past chunk end in %s %p", set->header.name, chunk); } #endif @@ -1034,7 +1073,7 @@ AllocSetFree(void *pointer) /* Test for someone scribbling on unused space in chunk */ if (chunk->requested_size < GetChunkSizeFromFreeListIdx(fidx)) if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", + elog(ERROR, "detected write past chunk end in %s %p", set->header.name, chunk); #endif @@ -1078,6 +1117,9 @@ AllocSetRealloc(void *pointer, Size size) MemoryChunk *chunk = PointerGetMemoryChunk(pointer); Size oldsize; + fprintf(stderr, "AllocSetRelloc %ld %ld %ld\n", size, pow2_size(size), pow2_size(size+1)); + fflush(stderr); + /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); @@ -1100,7 +1142,7 @@ AllocSetRealloc(void *pointer, Size size) /* Test for someone scribbling on unused space in chunk */ if (chunk->requested_size < oldsize) if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", + elog(ERROR, "detected write past chunk end in %s %p", set->header.name, chunk); #endif @@ -1111,7 +1153,7 @@ AllocSetRealloc(void *pointer, Size size) if (block->freeptr != block->endptr) elog(ERROR, "could not find block containing chunk %p", chunk); - chksize = MAXALIGN(size); + chksize = MAXALIGN(size+1); /* Do the realloc */ blksize = chksize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ; @@ -1163,7 +1205,16 @@ AllocSetRealloc(void *pointer, Size size) chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chksize) + { set_sentinel(pointer, size); + fprintf(stderr, "sentinel added\n"); + fflush(stderr); + } + else + { + fprintf(stderr, "D sentinel not added\n"); + fflush(stderr); + } #else /* !MEMORY_CONTEXT_CHECKING */ /* @@ -1191,7 +1242,7 @@ AllocSetRealloc(void *pointer, Size size) /* Test for someone scribbling on unused space in chunk */ if (chunk->requested_size < oldsize) if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", + elog(ERROR, "detected write past chunk end in %s %p", set->header.name, chunk); #endif @@ -1200,7 +1251,7 @@ AllocSetRealloc(void *pointer, Size size) * allocated area already is >= the new size. (In particular, we will * fall out here if the requested size is a decrease.) */ - if (oldsize >= size) + if (oldsize >= size + 1) { #ifdef MEMORY_CONTEXT_CHECKING Size oldrequest = chunk->requested_size; @@ -1227,7 +1278,17 @@ AllocSetRealloc(void *pointer, Size size) /* set mark to catch clobber of "unused" space */ if (size < oldsize) + { set_sentinel(pointer, size); + + fprintf(stderr, "sentinel added\n"); + fflush(stderr); + } + else + { + fprintf(stderr, "E sentinel not added\n"); + fflush(stderr); + } #else /* !MEMORY_CONTEXT_CHECKING */ /* @@ -1532,7 +1593,7 @@ AllocSetCheck(MemoryContext context) */ if (dsize != InvalidAllocSize && dsize < chsize && !sentinel_ok(chunk, ALLOC_CHUNKHDRSZ + dsize)) - elog(WARNING, "problem in alloc set %s: detected write past chunk end in block %p, chunk %p", + elog(ERROR, "problem in alloc set %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); /* diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index b39894ec94..2f1363967d 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -323,6 +323,15 @@ GenerationDelete(MemoryContext context) free(context); } +static Size pow2_size(Size size) +{ + Size s = 1; + while (s < size) + s *= 2; + + return s; +} + /* * GenerationAlloc * Returns pointer to allocated memory of given size or NULL if @@ -345,6 +354,9 @@ GenerationAlloc(MemoryContext context, Size size) Size chunk_size = MAXALIGN(size); Size required_size = chunk_size + Generation_CHUNKHDRSZ; + fprintf(stderr, "GenerationAlloc %ld %ld %ld\n", size, pow2_size(size), pow2_size(size+1)); + fflush(stderr); + /* is it an over-sized chunk? if yes, allocate special block */ if (chunk_size > set->allocChunkLimit) { @@ -709,6 +721,9 @@ GenerationRealloc(void *pointer, Size size) GenerationPointer newPointer; Size oldsize; + fprintf(stderr, "GenerationRealloc %ld %ld %ld\n", size, pow2_size(size), pow2_size(size+1)); + fflush(stderr); + /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN);
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-08-31 21:46  David Rowley <dgrowleyml@gmail.com>
  parent: Tomas Vondra <tomas.vondra@enterprisedb.com>
  0 siblings, 2 replies; 152+ messages in thread

From: David Rowley @ 2022-08-31 21:46 UTC (permalink / raw)
  To: Tomas Vondra <tomas.vondra@enterprisedb.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Thu, 1 Sept 2022 at 08:53, Tomas Vondra
<tomas.vondra@enterprisedb.com> wrote:
> So the raw size (what we asked for) is ~23.5GB, but in practice we
> allocate ~28.8GB because of the pow-of-2 logic. And by adding the extra
> 1B we end up allocating 31.5GB. That doesn't seem like a huge increase,
> and it's far from the +60% you got.
>
> I wonder where does the difference come - I did make installcheck too,
> so how come you get 10/16GB, and I get 28/31GB? My patch is attached,
> maybe I did something silly.

The reason my reported results were lower is because I ignored size >
allocChunkLimit allocations. These are not raised to the next power of
2, so I didn't think they should be included.

I'm not sure why you're seeing only a 3GB additional overhead. I
noticed a logic error in my query where I was checking
maxaligned_size=pow2_size and doubling that to give sentinel space.
That really should have been "case size=pow2_size then pow2_size * 2
else pow2_size end", However, after adjusting the query, it does not
seem to change the results much:

postgres=# select
postgres-# round(sum(pow2_Size)::numeric/1024/1024/1024,3) as pow2_size,
postgres-# round(sum(case when size=pow2_size then pow2_size*2 else
pow2_size end)::numeric/1024/1024/1024,3) as method1,
postgres-# round(sum(case when size=pow2_size then pow2_size+8 else
pow2_size end)::numeric/1024/1024/1024,3) as method2
postgres-# from memstats
postgres-# where pow2_size > 0;
 pow2_size | method1 | method2
-----------+---------+---------
    10.269 |  16.322 |  10.476

I've attached the crude patch I came up with for this.  For some
reason it was crashing on Linux, but it ran ok on Windows, so I used
the results from that instead.  Maybe that accounts for some
differences as e.g sizeof(long) == 4 on 64-bit windows. I'd be
surprised if that accounted for so many GBs though.

I also forgot to add code to GenerationRealloc and AllocSetRealloc

David

Attachments:

track_allocations.patch (text/plain, 1.8K) download diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index b6eeb8abab..f4977f9bcc 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -46,6 +46,7 @@ #include "postgres.h" +#include "miscadmin.h" #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" @@ -696,9 +697,22 @@ AllocSetAlloc(MemoryContext context, Size size) int fidx; Size chunk_size; Size blksize; + static int rlevel = 1; AssertArg(AllocSetIsValid(set)); + if (rlevel == 1 && GetProcessingMode() == NormalProcessing) + { + rlevel++; + elog(LOG, "AllocSetAlloc,%s,%zu,%zu,%zu,%zu", + context->name, + size, + MAXALIGN(size), + size > set->allocChunkLimit ? 0 : GetChunkSizeFromFreeListIdx(AllocSetFreeIndex(size)), + set->allocChunkLimit); + rlevel--; + } + /* * If requested size exceeds maximum for chunks, allocate an entire block * for this request. diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index b39894ec94..9c5ff3c095 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -36,6 +36,7 @@ #include "postgres.h" #include "lib/ilist.h" +#include "miscadmin.h" #include "port/pg_bitutils.h" #include "utils/memdebug.h" #include "utils/memutils.h" @@ -344,6 +345,18 @@ GenerationAlloc(MemoryContext context, Size size) MemoryChunk *chunk; Size chunk_size = MAXALIGN(size); Size required_size = chunk_size + Generation_CHUNKHDRSZ; + static int rlevel = 1; + + if (rlevel == 1 && GetProcessingMode() == NormalProcessing) + { + rlevel++; + elog(LOG, "GenerationAlloc,%s,%zu,%zu,0,%zu", + context->name, + size, + MAXALIGN(size), + set->allocChunkLimit); + rlevel--; + } /* is it an over-sized chunk? if yes, allocate special block */ if (chunk_size > set->allocChunkLimit)
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-01 00:12  Tomas Vondra <tomas.vondra@enterprisedb.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 0 replies; 152+ messages in thread

From: Tomas Vondra @ 2022-09-01 00:12 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>



On 8/31/22 23:46, David Rowley wrote:
> On Thu, 1 Sept 2022 at 08:53, Tomas Vondra
> <tomas.vondra@enterprisedb.com> wrote:
>> So the raw size (what we asked for) is ~23.5GB, but in practice we
>> allocate ~28.8GB because of the pow-of-2 logic. And by adding the extra
>> 1B we end up allocating 31.5GB. That doesn't seem like a huge increase,
>> and it's far from the +60% you got.
>>
>> I wonder where does the difference come - I did make installcheck too,
>> so how come you get 10/16GB, and I get 28/31GB? My patch is attached,
>> maybe I did something silly.
> 
> The reason my reported results were lower is because I ignored size >
> allocChunkLimit allocations. These are not raised to the next power of
> 2, so I didn't think they should be included.

If I differentiate the large chunks allocated separately (v2 patch
attached), I get this:

        f        |    t     |  count   |       s1 |       s2 |       s3
-----------------+----------+----------+----------+----------+----------
 AllocSetAlloc   | normal   | 60714914 |     4982 |     6288 |     8185
 AllocSetAlloc   | separate |   824390 |    18245 |    18245 |    18251
 AllocSetRelloc  | normal   |   182070 |      763 |      826 |     1423
 GenerationAlloc | normal   |  2118115 |       68 |       90 |      102
 GenerationAlloc | separate |       28 |        0 |        0 |        0
(5 rows)

Where s1 is the sum of requested sizes, s2 is the sum of allocated
chunks, and s3 is chunks allocated with 1B sentinel.

Focusing on the aset, vast majority of allocations (60M out of 64M) is
small enough to use power-of-2 logic, and we go from 6.3GB to 8.2GB, so
~30%. Not great, not terrible.

For the large allocations, there's almost no increase - in the last
query I used the power-of-2 logic in the calculations, but that was
incorrect, of course.


> 
> I'm not sure why you're seeing only a 3GB additional overhead. I
> noticed a logic error in my query where I was checking
> maxaligned_size=pow2_size and doubling that to give sentinel space.
> That really should have been "case size=pow2_size then pow2_size * 2
> else pow2_size end", However, after adjusting the query, it does not
> seem to change the results much:
> 
> postgres=# select
> postgres-# round(sum(pow2_Size)::numeric/1024/1024/1024,3) as pow2_size,
> postgres-# round(sum(case when size=pow2_size then pow2_size*2 else
> pow2_size end)::numeric/1024/1024/1024,3) as method1,
> postgres-# round(sum(case when size=pow2_size then pow2_size+8 else
> pow2_size end)::numeric/1024/1024/1024,3) as method2
> postgres-# from memstats
> postgres-# where pow2_size > 0;
>  pow2_size | method1 | method2
> -----------+---------+---------
>     10.269 |  16.322 |  10.476
> 
> I've attached the crude patch I came up with for this.  For some
> reason it was crashing on Linux, but it ran ok on Windows, so I used
> the results from that instead.  Maybe that accounts for some
> differences as e.g sizeof(long) == 4 on 64-bit windows. I'd be
> surprised if that accounted for so many GBs though.
> 

I tried to use that patch, but "make installcheck" never completes for
me, for some reason. It seems to get stuck in infinite_recurse.sql, but
I haven't looked into the details.


regards

-- 
Tomas Vondra
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

Attachments:

sentinel-tweak-v2.patch (text/x-patch, 9.2K) download diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index b6eeb8abab..b215940062 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -674,6 +674,15 @@ AllocSetDelete(MemoryContext context) free(set); } +static Size pow2_size(Size size) +{ + Size s = 1; + while (s < size) + s *= 2; + + return s; +} + /* * AllocSetAlloc * Returns pointer to allocated memory of given size or NULL if @@ -703,9 +712,12 @@ AllocSetAlloc(MemoryContext context, Size size) * If requested size exceeds maximum for chunks, allocate an entire block * for this request. */ - if (size > set->allocChunkLimit) + if (size + 1 > set->allocChunkLimit) { - chunk_size = MAXALIGN(size); + fprintf(stderr, "AllocSetAlloc separate %ld %ld %ld\n", size, MAXALIGN(size), MAXALIGN(size+1)); + fflush(stderr); + + chunk_size = MAXALIGN(size+1); blksize = chunk_size + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ; block = (AllocBlock) malloc(blksize); if (block == NULL) @@ -726,6 +738,11 @@ AllocSetAlloc(MemoryContext context, Size size) /* set mark to catch clobber of "unused" space */ if (size < chunk_size) set_sentinel(MemoryChunkGetPointer(chunk), size); + else + { + fprintf(stderr, "sentinel not added\n"); + fflush(stderr); + } #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ @@ -761,13 +778,16 @@ AllocSetAlloc(MemoryContext context, Size size) return MemoryChunkGetPointer(chunk); } + fprintf(stderr, "AllocSetAlloc normal %ld %ld %ld\n", size, pow2_size(size), pow2_size(size+1)); + fflush(stderr); + /* * Request is small enough to be treated as a chunk. Look in the * corresponding free list to see if there is a free chunk we could reuse. * If one is found, remove it from the free list, make it again a member * of the alloc set and return its data address. */ - fidx = AllocSetFreeIndex(size); + fidx = AllocSetFreeIndex(size+1); chunk = set->freelist[fidx]; if (chunk != NULL) { @@ -785,6 +805,11 @@ AllocSetAlloc(MemoryContext context, Size size) /* set mark to catch clobber of "unused" space */ if (size < GetChunkSizeFromFreeListIdx(fidx)) set_sentinel(MemoryChunkGetPointer(chunk), size); + else + { + fprintf(stderr, "sentinel not added\n"); + fflush(stderr); + } #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ @@ -951,6 +976,11 @@ AllocSetAlloc(MemoryContext context, Size size) /* set mark to catch clobber of "unused" space */ if (size < chunk_size) set_sentinel(MemoryChunkGetPointer(chunk), size); + else + { + fprintf(stderr, "sentinel not added\n"); + fflush(stderr); + } #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ @@ -994,7 +1024,7 @@ AllocSetFree(void *pointer) /* Test for someone scribbling on unused space in chunk */ if (chunk->requested_size < chunk_size) if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", + elog(ERROR, "detected write past chunk end in %s %p", set->header.name, chunk); } #endif @@ -1034,7 +1064,7 @@ AllocSetFree(void *pointer) /* Test for someone scribbling on unused space in chunk */ if (chunk->requested_size < GetChunkSizeFromFreeListIdx(fidx)) if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", + elog(ERROR, "detected write past chunk end in %s %p", set->header.name, chunk); #endif @@ -1078,6 +1108,9 @@ AllocSetRealloc(void *pointer, Size size) MemoryChunk *chunk = PointerGetMemoryChunk(pointer); Size oldsize; + fprintf(stderr, "AllocSetRelloc normal %ld %ld %ld\n", size, pow2_size(size), pow2_size(size+1)); + fflush(stderr); + /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); @@ -1100,7 +1133,7 @@ AllocSetRealloc(void *pointer, Size size) /* Test for someone scribbling on unused space in chunk */ if (chunk->requested_size < oldsize) if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", + elog(ERROR, "detected write past chunk end in %s %p", set->header.name, chunk); #endif @@ -1111,7 +1144,7 @@ AllocSetRealloc(void *pointer, Size size) if (block->freeptr != block->endptr) elog(ERROR, "could not find block containing chunk %p", chunk); - chksize = MAXALIGN(size); + chksize = MAXALIGN(size+1); /* Do the realloc */ blksize = chksize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ; @@ -1164,6 +1197,11 @@ AllocSetRealloc(void *pointer, Size size) /* set mark to catch clobber of "unused" space */ if (size < chksize) set_sentinel(pointer, size); + else + { + fprintf(stderr, "sentinel not added\n"); + fflush(stderr); + } #else /* !MEMORY_CONTEXT_CHECKING */ /* @@ -1191,7 +1229,7 @@ AllocSetRealloc(void *pointer, Size size) /* Test for someone scribbling on unused space in chunk */ if (chunk->requested_size < oldsize) if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", + elog(ERROR, "detected write past chunk end in %s %p", set->header.name, chunk); #endif @@ -1200,7 +1238,7 @@ AllocSetRealloc(void *pointer, Size size) * allocated area already is >= the new size. (In particular, we will * fall out here if the requested size is a decrease.) */ - if (oldsize >= size) + if (oldsize >= size + 1) { #ifdef MEMORY_CONTEXT_CHECKING Size oldrequest = chunk->requested_size; @@ -1228,6 +1266,11 @@ AllocSetRealloc(void *pointer, Size size) /* set mark to catch clobber of "unused" space */ if (size < oldsize) set_sentinel(pointer, size); + else + { + fprintf(stderr, "sentinel not added\n"); + fflush(stderr); + } #else /* !MEMORY_CONTEXT_CHECKING */ /* @@ -1532,7 +1575,7 @@ AllocSetCheck(MemoryContext context) */ if (dsize != InvalidAllocSize && dsize < chsize && !sentinel_ok(chunk, ALLOC_CHUNKHDRSZ + dsize)) - elog(WARNING, "problem in alloc set %s: detected write past chunk end in block %p, chunk %p", + elog(ERROR, "problem in alloc set %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); /* diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index b39894ec94..0029edb31e 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -323,6 +323,15 @@ GenerationDelete(MemoryContext context) free(context); } +static Size pow2_size(Size size) +{ + Size s = 1; + while (s < size) + s *= 2; + + return s; +} + /* * GenerationAlloc * Returns pointer to allocated memory of given size or NULL if @@ -342,7 +351,7 @@ GenerationAlloc(MemoryContext context, Size size) GenerationContext *set = (GenerationContext *) context; GenerationBlock *block; MemoryChunk *chunk; - Size chunk_size = MAXALIGN(size); + Size chunk_size = MAXALIGN(size+1); Size required_size = chunk_size + Generation_CHUNKHDRSZ; /* is it an over-sized chunk? if yes, allocate special block */ @@ -350,6 +359,9 @@ GenerationAlloc(MemoryContext context, Size size) { Size blksize = required_size + Generation_BLOCKHDRSZ; + fprintf(stderr, "GenerationAlloc separate %ld %ld %ld\n", size, MAXALIGN(size), MAXALIGN(size+1)); + fflush(stderr); + block = (GenerationBlock *) malloc(blksize); if (block == NULL) return NULL; @@ -375,6 +387,11 @@ GenerationAlloc(MemoryContext context, Size size) /* set mark to catch clobber of "unused" space */ if (size < chunk_size) set_sentinel(MemoryChunkGetPointer(chunk), size); + else + { + fprintf(stderr, "sentinel not added\n"); + fflush(stderr); + } #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ @@ -394,6 +411,9 @@ GenerationAlloc(MemoryContext context, Size size) return MemoryChunkGetPointer(chunk); } + fprintf(stderr, "GenerationAlloc normal %ld %ld %ld\n", size, pow2_size(size), pow2_size(size+1)); + fflush(stderr); + /* * Not an oversized chunk. We try to first make use of the current block, * but if there's not enough space in it, instead of allocating a new @@ -493,6 +513,11 @@ GenerationAlloc(MemoryContext context, Size size) /* set mark to catch clobber of "unused" space */ if (size < chunk_size) set_sentinel(MemoryChunkGetPointer(chunk), size); + else + { + fprintf(stderr, "sentinel not added\n"); + fflush(stderr); + } #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ @@ -709,6 +734,9 @@ GenerationRealloc(void *pointer, Size size) GenerationPointer newPointer; Size oldsize; + fprintf(stderr, "GenerationRealloc normal %ld %ld %ld\n", size, MAXALIGN(size), MAXALIGN(size+1)); + fflush(stderr); + /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); @@ -771,6 +799,11 @@ GenerationRealloc(void *pointer, Size size) /* set mark to catch clobber of "unused" space */ if (size < oldsize) set_sentinel(pointer, size); + else + { + fprintf(stderr, "sentinel not added\n"); + fflush(stderr); + } #else /* !MEMORY_CONTEXT_CHECKING */ /*
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-01 00:23  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 3 replies; 152+ messages in thread

From: Tom Lane @ 2022-09-01 00:23 UTC (permalink / raw)
  To: Tomas Vondra <tomas.vondra@enterprisedb.com>; +Cc: David Rowley <dgrowleyml@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Tomas Vondra <tomas.vondra@enterprisedb.com> writes:
> Focusing on the aset, vast majority of allocations (60M out of 64M) is
> small enough to use power-of-2 logic, and we go from 6.3GB to 8.2GB, so
> ~30%. Not great, not terrible.

Not sure why this escaped me before, but I remembered another argument
for not forcibly adding space for a sentinel: if you don't have room,
that means the chunk end is up against the header for the next chunk,
which means that any buffer overrun will clobber that header.  So we'll
detect the problem anyway if we validate the headers to a reasonable
extent.

The hole in this argument is that the very last chunk allocated in a
block might have no following chunk to validate.  But we could probably
special-case that somehow, maybe by laying down a sentinel in the free
space, where it will get overwritten by the next chunk when that does
get allocated.

30% memory bloat seems like a high price to pay if it's adding negligible
detection ability, which it seems is true if this argument is valid.
Is there reason to think we can't validate headers enough to catch
clobbers?

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-01 00:31  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  2 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-09-01 00:31 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Thu, 1 Sept 2022 at 12:23, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Is there reason to think we can't validate headers enough to catch
> clobbers?

For non-sentinel chunks, the next byte after the end of the chunk will
be storing the block offset for the following chunk.  I think:

if (block != MemoryChunkGetBlock(chunk))
elog(WARNING, "problem in alloc set %s: bad block offset for chunk %p
in block %p",
name, chunk, block);

should catch those.

Maybe we should just consider always making room for a sentinel for
chunks that are on dedicated blocks. At most that's an extra 8 bytes
in some allocation that's either over 1024 or 8192 (depending on
maxBlockSize).

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-01 00:46  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-09-01 00:46 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> Maybe we should just consider always making room for a sentinel for
> chunks that are on dedicated blocks. At most that's an extra 8 bytes
> in some allocation that's either over 1024 or 8192 (depending on
> maxBlockSize).

Agreed, if we're not doing that already then we should.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-01 00:49  Tomas Vondra <tomas.vondra@enterprisedb.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  2 siblings, 0 replies; 152+ messages in thread

From: Tomas Vondra @ 2022-09-01 00:49 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: David Rowley <dgrowleyml@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>



On 9/1/22 02:23, Tom Lane wrote:
> Tomas Vondra <tomas.vondra@enterprisedb.com> writes:
>> Focusing on the aset, vast majority of allocations (60M out of 64M) is
>> small enough to use power-of-2 logic, and we go from 6.3GB to 8.2GB, so
>> ~30%. Not great, not terrible.
> 
> Not sure why this escaped me before, but I remembered another argument
> for not forcibly adding space for a sentinel: if you don't have room,
> that means the chunk end is up against the header for the next chunk,
> which means that any buffer overrun will clobber that header.  So we'll
> detect the problem anyway if we validate the headers to a reasonable
> extent.
> 
> The hole in this argument is that the very last chunk allocated in a
> block might have no following chunk to validate.  But we could probably
> special-case that somehow, maybe by laying down a sentinel in the free
> space, where it will get overwritten by the next chunk when that does
> get allocated.
> 
> 30% memory bloat seems like a high price to pay if it's adding negligible
> detection ability, which it seems is true if this argument is valid.
> Is there reason to think we can't validate headers enough to catch
> clobbers?
> 

I'm not quite convinced the 30% figure is correct - it might be if you
ignore cases exceeding allocChunkLimit, but that also makes it pretty
bogus (because large allocations represent ~2x as much space).

You're probably right we'll notice the clobber cases due to corruption
of the next chunk header. The annoying thing is having a corrupted
header only tells you there's a corruption somewhere, but it may be hard
to know which part of the code caused it. I was hoping the sentinel
would make it easier, because we mark it as NOACCESS for valgrind. But
now I see we mark the first part of a MemoryChunk too, so maybe that's
enough.

OTOH we have platforms where valgrind is either not supported or no one
runs tests with (e.g. on rpi4 it'd take insane amounts of code). In that
case the sentinel might be helpful, especially considering alignment on
those platforms can cause funny memory issues, as evidenced by this thread.

regards

-- 
Tomas Vondra
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-01 01:06  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  2 siblings, 0 replies; 152+ messages in thread

From: Tom Lane @ 2022-09-01 01:06 UTC (permalink / raw)
  To: Tomas Vondra <tomas.vondra@enterprisedb.com>; +Cc: David Rowley <dgrowleyml@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Tomas Vondra <tomas.vondra@enterprisedb.com> writes:
> You're probably right we'll notice the clobber cases due to corruption
> of the next chunk header. The annoying thing is having a corrupted
> header only tells you there's a corruption somewhere, but it may be hard
> to know which part of the code caused it.

Same's true of a sentinel, though.

> OTOH we have platforms where valgrind is either not supported or no one
> runs tests with (e.g. on rpi4 it'd take insane amounts of code).

According to
https://valgrind.org/info/platforms.html
valgrind supports a pretty respectable set of platforms.  It might
be too slow to be useful on ancient hardware, of course.

I've had some success in identifying clobber perpetrators by putting
a hardware watchpoint on the clobbered word, which IIRC does work on
recent ARM hardware.  It's tedious and far more manual than valgrind,
but it's possible.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-01 03:15  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  2 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-09-01 03:15 UTC (permalink / raw)
  To: Tomas Vondra <tomas.vondra@enterprisedb.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 30 Aug 2022 at 13:16, David Rowley <dgrowleyml@gmail.com> wrote:
> I'm also wondering if this should also be backpatched back to v10,
> providing the build farm likes it well enough on master.

Does anyone have any objections to d5ee4db0e in its entirety being backpatched?

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-01 04:06  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-09-01 04:06 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> Does anyone have any objections to d5ee4db0e in its entirety being backpatched?

It doesn't seem to be fixing any live bug in the back branches,
but by the same token it's harmless.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-01 04:08  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-09-01 04:08 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Thu, 1 Sept 2022 at 16:06, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> David Rowley <dgrowleyml@gmail.com> writes:
> > Does anyone have any objections to d5ee4db0e in its entirety being backpatched?
>
> It doesn't seem to be fixing any live bug in the back branches,
> but by the same token it's harmless.

I considered that an extension might use the Slab allocator with a
non-MAXALIGNED chunksize and might run into some troubles during
SlabCheck().

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-01 04:19  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 0 replies; 152+ messages in thread

From: Tom Lane @ 2022-09-01 04:19 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> On Thu, 1 Sept 2022 at 16:06, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> It doesn't seem to be fixing any live bug in the back branches,
>> but by the same token it's harmless.

> I considered that an extension might use the Slab allocator with a
> non-MAXALIGNED chunksize and might run into some troubles during
> SlabCheck().

Oh, yeah, the sentinel_ok() change is a live bug.  Extensions
have no control over sizeof(SlabBlock) though.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-01 13:27  Ranier Vilela <ranier.vf@gmail.com>
  0 siblings, 0 replies; 152+ messages in thread

From: Ranier Vilela @ 2022-09-01 13:27 UTC (permalink / raw)
  To: pgsql-hackers; +Cc: David Rowley <dgrowleyml@gmail.com>; Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>

Hi,
Excuse me for posting on this thread.

Coverity has a complaints about aset.c
CID 1497225 (#1 of 2): Out-of-bounds write (OVERRUN)3. overrun-local:
Overrunning
array set->freelist of 11 8-byte elements at element index 1073741823 (byte
offset 8589934591) using index fidx (which evaluates to 1073741823).

CID 1497225 (#2 of 2): Out-of-bounds write (OVERRUN)3. overrun-local:
Overrunning
array set->freelist of 11 8-byte elements at element index 1073741823 (byte
offset 8589934591) using index fidx (which evaluates to 1073741823).

I think that this is an oversight.

inline patch 1: src/backend/utils/mmgr/aset.c (+1/-1 lines) download inline-1.patchdiff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index b6eeb8abab..8f709514b2 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -1024,7 +1024,7 @@ AllocSetFree(void *pointer) } else { - int fidx = MemoryChunkGetValue(chunk); + Size fidx = MemoryChunkGetValue(chunk); AllocBlock block = MemoryChunkGetBlock(chunk); AllocFreeListLink *link = GetFreeListLink(chunk);
MemoryChunkGetValue return Size not int. Not sure if this fix is enough. regards, Ranier Vilela ^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-02 08:11  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-09-02 08:11 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Thu, 1 Sept 2022 at 12:46, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> David Rowley <dgrowleyml@gmail.com> writes:
> > Maybe we should just consider always making room for a sentinel for
> > chunks that are on dedicated blocks. At most that's an extra 8 bytes
> > in some allocation that's either over 1024 or 8192 (depending on
> > maxBlockSize).
>
> Agreed, if we're not doing that already then we should.

Here's a patch to that effect.

I've made it so that there's always space for the sentinel for all
generation.c and slab.c allocations. There is no power of 2 rounding
with those, so no concern about doubling the memory for power-of-2
sized allocations.

With aset.c, I'm only adding sentinel space when size >
allocChunkLimit, aka external chunks.

David

Attachments:

v1-0001-Make-more-effort-to-have-a-sentinel-byte-in-memor.patch (text/plain, 10.5K) download From a61c1646987996192ef9e917ca0fabbef51e34c9 Mon Sep 17 00:00:00 2001 From: David Rowley <dgrowley@gmail.com> Date: Fri, 2 Sep 2022 13:30:06 +1200 Subject: [PATCH v1] Make more effort to have a sentinel byte in memory contexts --- src/backend/utils/mmgr/aset.c | 41 +++++++++++++++++++-------- src/backend/utils/mmgr/generation.c | 43 +++++++++++++++++------------ src/backend/utils/mmgr/slab.c | 37 +++++++++++++------------ 3 files changed, 74 insertions(+), 47 deletions(-) diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index b6eeb8abab..ec423375ae 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -705,7 +705,13 @@ AllocSetAlloc(MemoryContext context, Size size) */ if (size > set->allocChunkLimit) { +#ifdef MEMORY_CONTEXT_CHECKING + /* ensure there's always space for the sentinel byte */ + chunk_size = MAXALIGN(size + 1); +#else chunk_size = MAXALIGN(size); +#endif + blksize = chunk_size + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ; block = (AllocBlock) malloc(blksize); if (block == NULL) @@ -724,8 +730,8 @@ AllocSetAlloc(MemoryContext context, Size size) #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk_size) - set_sentinel(MemoryChunkGetPointer(chunk), size); + Assert(size < chunk_size); + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ @@ -766,6 +772,12 @@ AllocSetAlloc(MemoryContext context, Size size) * corresponding free list to see if there is a free chunk we could reuse. * If one is found, remove it from the free list, make it again a member * of the alloc set and return its data address. + * + * Note that we don't attempt to ensure there's space for the sentinel + * byte here. We expect a large proportion of allocations to be for sizes + * which are already a power of 2. If we were to always make space for a + * sentinel byte in MEMORY_CONTEXT_CHECKING builds, then we'd end up + * doubling the memory requirements for such allocations. */ fidx = AllocSetFreeIndex(size); chunk = set->freelist[fidx]; @@ -992,10 +1004,10 @@ AllocSetFree(void *pointer) Size chunk_size = block->endptr - (char *) pointer; /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunk_size) - if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", - set->header.name, chunk); + Assert(chunk->requested_size < chunk_size); + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); } #endif @@ -1098,10 +1110,10 @@ AllocSetRealloc(void *pointer, Size size) #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < oldsize) - if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", - set->header.name, chunk); + Assert(chunk->requested_size < oldsize); + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + set->header.name, chunk); #endif /* @@ -1111,7 +1123,12 @@ AllocSetRealloc(void *pointer, Size size) if (block->freeptr != block->endptr) elog(ERROR, "could not find block containing chunk %p", chunk); +#ifdef MEMORY_CONTEXT_CHECKING + /* ensure there's always space for the sentinel byte */ + chksize = MAXALIGN(size + 1); +#else chksize = MAXALIGN(size); +#endif /* Do the realloc */ blksize = chksize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ; @@ -1162,8 +1179,8 @@ AllocSetRealloc(void *pointer, Size size) chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chksize) - set_sentinel(pointer, size); + Assert(size < chksize); + set_sentinel(pointer, size); #else /* !MEMORY_CONTEXT_CHECKING */ /* diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index b39894ec94..c743b24fa7 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -342,8 +342,16 @@ GenerationAlloc(MemoryContext context, Size size) GenerationContext *set = (GenerationContext *) context; GenerationBlock *block; MemoryChunk *chunk; - Size chunk_size = MAXALIGN(size); - Size required_size = chunk_size + Generation_CHUNKHDRSZ; + Size chunk_size; + Size required_size; + +#ifdef MEMORY_CONTEXT_CHECKING + /* ensure there's always space for the sentinel byte */ + chunk_size = MAXALIGN(size + 1); +#else + chunk_size = MAXALIGN(size); +#endif + required_size = chunk_size + Generation_CHUNKHDRSZ; /* is it an over-sized chunk? if yes, allocate special block */ if (chunk_size > set->allocChunkLimit) @@ -373,8 +381,8 @@ GenerationAlloc(MemoryContext context, Size size) #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk_size) - set_sentinel(MemoryChunkGetPointer(chunk), size); + Assert(size < chunk_size); + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ @@ -491,8 +499,8 @@ GenerationAlloc(MemoryContext context, Size size) #ifdef MEMORY_CONTEXT_CHECKING chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ - if (size < chunk_size) - set_sentinel(MemoryChunkGetPointer(chunk), size); + Assert(size < chunk_size); + set_sentinel(MemoryChunkGetPointer(chunk), size); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY /* fill the allocated space with junk */ @@ -634,10 +642,10 @@ GenerationFree(void *pointer) #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < chunksize) - if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", - ((MemoryContext) block->context)->name, chunk); + Assert(chunk->requested_size < chunksize); + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + ((MemoryContext) block->context)->name, chunk); #endif #ifdef CLOBBER_FREED_MEMORY @@ -727,10 +735,10 @@ GenerationRealloc(void *pointer, Size size) #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (chunk->requested_size < oldsize) - if (!sentinel_ok(pointer, chunk->requested_size)) - elog(WARNING, "detected write past chunk end in %s %p", - ((MemoryContext) set)->name, chunk); + Assert(chunk->requested_size < oldsize); + if (!sentinel_ok(pointer, chunk->requested_size)) + elog(WARNING, "detected write past chunk end in %s %p", + ((MemoryContext) set)->name, chunk); #endif /* @@ -769,8 +777,7 @@ GenerationRealloc(void *pointer, Size size) oldsize - size); /* set mark to catch clobber of "unused" space */ - if (size < oldsize) - set_sentinel(pointer, size); + set_sentinel(pointer, size); #else /* !MEMORY_CONTEXT_CHECKING */ /* @@ -1034,8 +1041,8 @@ GenerationCheck(MemoryContext context) name, block, chunk); /* check sentinel */ - if (chunk->requested_size < chunksize && - !sentinel_ok(chunk, Generation_CHUNKHDRSZ + chunk->requested_size)) + Assert(chunk->requested_size < chunksize); + if (!sentinel_ok(chunk, Generation_CHUNKHDRSZ + chunk->requested_size)) elog(WARNING, "problem in Generation %s: detected write past chunk end in block %p, chunk %p", name, block, chunk); } diff --git a/src/backend/utils/mmgr/slab.c b/src/backend/utils/mmgr/slab.c index 2d70adef09..9149aaafcb 100644 --- a/src/backend/utils/mmgr/slab.c +++ b/src/backend/utils/mmgr/slab.c @@ -145,7 +145,12 @@ SlabContextCreate(MemoryContext parent, chunkSize = sizeof(int); /* chunk, including SLAB header (both addresses nicely aligned) */ +#ifdef MEMORY_CONTEXT_CHECKING + /* ensure there's always space for the sentinel byte */ + fullChunkSize = Slab_CHUNKHDRSZ + MAXALIGN(chunkSize + 1); +#else fullChunkSize = Slab_CHUNKHDRSZ + MAXALIGN(chunkSize); +#endif /* Make sure the block can store at least one chunk. */ if (blockSize < fullChunkSize + Slab_BLOCKHDRSZ) @@ -420,14 +425,12 @@ SlabAlloc(MemoryContext context, Size size) MCTX_SLAB_ID); #ifdef MEMORY_CONTEXT_CHECKING /* slab mark to catch clobber of "unused" space */ - if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) - { - set_sentinel(MemoryChunkGetPointer(chunk), size); - VALGRIND_MAKE_MEM_NOACCESS(((char *) chunk) + - Slab_CHUNKHDRSZ + slab->chunkSize, - slab->fullChunkSize - - (slab->chunkSize + Slab_CHUNKHDRSZ)); - } + Assert(slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)); + set_sentinel(MemoryChunkGetPointer(chunk), size); + VALGRIND_MAKE_MEM_NOACCESS(((char *) chunk) + + Slab_CHUNKHDRSZ + slab->chunkSize, + slab->fullChunkSize - + (slab->chunkSize + Slab_CHUNKHDRSZ)); #endif #ifdef RANDOMIZE_ALLOCATED_MEMORY @@ -454,10 +457,10 @@ SlabFree(void *pointer) #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ - if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) - if (!sentinel_ok(pointer, slab->chunkSize)) - elog(WARNING, "detected write past chunk end in %s %p", - slab->header.name, chunk); + Assert(slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)); + if (!sentinel_ok(pointer, slab->chunkSize)) + elog(WARNING, "detected write past chunk end in %s %p", + slab->header.name, chunk); #endif /* compute index of the chunk with respect to block start */ @@ -744,11 +747,11 @@ SlabCheck(MemoryContext context) elog(WARNING, "problem in slab %s: bogus block link in block %p, chunk %p", name, block, chunk); - /* there might be sentinel (thanks to alignment) */ - if (slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)) - if (!sentinel_ok(chunk, Slab_CHUNKHDRSZ + slab->chunkSize)) - elog(WARNING, "problem in slab %s: detected write past chunk end in block %p, chunk %p", - name, block, chunk); + /* check the sentinel byte is intact */ + Assert(slab->chunkSize < (slab->fullChunkSize - Slab_CHUNKHDRSZ)); + if (!sentinel_ok(chunk, Slab_CHUNKHDRSZ + slab->chunkSize)) + elog(WARNING, "problem in slab %s: detected write past chunk end in block %p, chunk %p", + name, block, chunk); } } -- 2.34.1
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-05 13:41  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-09-05 13:41 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Fri, 2 Sept 2022 at 20:11, David Rowley <dgrowleyml@gmail.com> wrote:
>
> On Thu, 1 Sept 2022 at 12:46, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> >
> > David Rowley <dgrowleyml@gmail.com> writes:
> > > Maybe we should just consider always making room for a sentinel for
> > > chunks that are on dedicated blocks. At most that's an extra 8 bytes
> > > in some allocation that's either over 1024 or 8192 (depending on
> > > maxBlockSize).
> >
> > Agreed, if we're not doing that already then we should.
>
> Here's a patch to that effect.

If there are no objections, then I plan to push that patch soon.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-05 23:09  Andres Freund <andres@anarazel.de>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 1 reply; 152+ messages in thread

From: Andres Freund @ 2022-09-05 23:09 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2022-08-29 17:26:29 +1200, David Rowley wrote:
> On Mon, 29 Aug 2022 at 10:39, David Rowley <dgrowleyml@gmail.com> wrote:
> > One more try to make CFbot happy.
>
> After a bit more revision, mostly updating outdated comments and
> naming adjustments, I've pushed this.

Responding to Tom's email about guc.c changes [1], I was looking at
MemoryContextContains(). Unless I am missing something, the patch omitted
adjusting that? We'll probably always return false right now.

Probably should have something that tests that MemoryContextContains() works
at least to some degree. Perhaps a test in regress.c?

Greetings,

Andres Freund

[1] https://postgr.es/m/2982579.1662416866%40sss.pgh.pa.us





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-06 00:10  David Rowley <dgrowleyml@gmail.com>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-09-06 00:10 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 6 Sept 2022 at 11:09, Andres Freund <andres@anarazel.de> wrote:
> I was looking at
> MemoryContextContains(). Unless I am missing something, the patch omitted
> adjusting that? We'll probably always return false right now.

Oops. Yes. I'll push a fix a bit later.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-06 00:27  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-09-06 00:27 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> On Tue, 6 Sept 2022 at 11:09, Andres Freund <andres@anarazel.de> wrote:
>> I was looking at
>> MemoryContextContains(). Unless I am missing something, the patch omitted
>> adjusting that? We'll probably always return false right now.

> Oops. Yes. I'll push a fix a bit later.

The existing uses in nodeAgg and nodeWindowAgg failed to expose this
because an incorrect false result just causes them to do extra work
(ie, a useless datumCopy).  I think there might be a memory leak
too, but the regression tests wouldn't run an aggregation long
enough to make that obvious either.

+1 for adding something to regress.c that verifies that this
works properly for all three allocators.  I suggest making
three contexts and cross-checking the correct results for
all combinations of chunk A vs context B.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-06 02:32  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 2 replies; 152+ messages in thread

From: David Rowley @ 2022-09-06 02:32 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 6 Sept 2022 at 12:27, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> David Rowley <dgrowleyml@gmail.com> writes:
> > On Tue, 6 Sept 2022 at 11:09, Andres Freund <andres@anarazel.de> wrote:
> >> I was looking at
> >> MemoryContextContains(). Unless I am missing something, the patch omitted
> >> adjusting that? We'll probably always return false right now.
>
> > Oops. Yes. I'll push a fix a bit later.

I think the fix is harder than I thought, or perhaps impossible to do
given how we now determine the owning MemoryContext of a pointer.

There's a comment in MemoryContextContains which says:

* NB: Can't use GetMemoryChunkContext() here - that performs assertions
* that aren't acceptable here since we might be passed memory not
* allocated by any memory context.

That seems to indicate that we should be able to handle any random
pointer given to us (!).  That comment seems more confident that'll
work than the function's header comment does:

 * Caution: this test is reliable as long as 'pointer' does point to
 * a chunk of memory allocated from *some* context.  If 'pointer' points
 * at memory obtained in some other way, there is a small chance of a
 * false-positive result, since the bits right before it might look like
 * a valid chunk header by chance.

Here that's just claiming the test might not be reliable and could
return false-positive results.

I find this entire function pretty scary as even before the context
changes that function seems to think it's fine to subtract sizeof(void
*) from the given pointer and dereference that memory. That could very
well segfault.

I wonder if there are many usages of MemoryContextContains in
extensions. If there's not, I'd be much happier if we got rid of this
function and used GetMemoryChunkContext() in nodeAgg.c and
nodeWindowAgg.c.

> +1 for adding something to regress.c that verifies that this
> works properly for all three allocators.  I suggest making
> three contexts and cross-checking the correct results for
> all combinations of chunk A vs context B.

I went as far as adding an Assert to palloc(). I'm not quite sure what
you have in mind in regress.c

Attached is a draft patch. I just don't like this function one bit.

David

Attachments:

draft_MemoryContextContains_fixes.patch (text/plain, 1.9K) download diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index 64bcc7ef32..a6b2d02b75 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -809,11 +809,10 @@ MemoryContextCheck(MemoryContext context) * Detect whether an allocated chunk of memory belongs to a given * context or not. * - * Caution: this test is reliable as long as 'pointer' does point to - * a chunk of memory allocated from *some* context. If 'pointer' points - * at memory obtained in some other way, there is a small chance of a - * false-positive result, since the bits right before it might look like - * a valid chunk header by chance. + * Caution: 'pointer' must point to a pointer which was allocated by a + * MemoryContext. It's not safe or valid to use this function on arbitrary + * pointers as obtaining the MemoryContext which 'pointer' belongs to requires + * possibly several pointer dereferences. */ bool MemoryContextContains(MemoryContext context, void *pointer) @@ -821,10 +820,6 @@ MemoryContextContains(MemoryContext context, void *pointer) MemoryContext ptr_context; /* - * NB: Can't use GetMemoryChunkContext() here - that performs assertions - * that aren't acceptable here since we might be passed memory not - * allocated by any memory context. - * * Try to detect bogus pointers handed to us, poorly though we can. * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an * allocated chunk. @@ -835,7 +830,7 @@ MemoryContextContains(MemoryContext context, void *pointer) /* * OK, it's probably safe to look at the context. */ - ptr_context = *(MemoryContext *) (((char *) pointer) - sizeof(void *)); + ptr_context = GetMemoryChunkContext(pointer); return ptr_context == context; } @@ -1151,6 +1146,8 @@ palloc(Size size) size, context->name))); } + Assert(MemoryContextContains(context, ret)); + VALGRIND_MEMPOOL_ALLOC(context, ret, size); return ret;
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-06 02:35  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 0 replies; 152+ messages in thread

From: David Rowley @ 2022-09-06 02:35 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 6 Sept 2022 at 14:32, David Rowley <dgrowleyml@gmail.com> wrote:
> I wonder if there are many usages of MemoryContextContains in
> extensions. If there's not, I'd be much happier if we got rid of this
> function and used GetMemoryChunkContext() in nodeAgg.c and
> nodeWindowAgg.c.

I see postgis is one user of it, per [1].  The other extensions
mentioned there just seem to be copying code and not using it.

David

[1] https://codesearch.debian.net/search?q=MemoryContextContains&literal=1





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-06 02:43  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-09-06 02:43 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> I think the fix is harder than I thought, or perhaps impossible to do
> given how we now determine the owning MemoryContext of a pointer.

> There's a comment in MemoryContextContains which says:

> * NB: Can't use GetMemoryChunkContext() here - that performs assertions
> * that aren't acceptable here since we might be passed memory not
> * allocated by any memory context.

I think MemoryContextContains' charter is to return

	GetMemoryChunkContext(pointer) == context

*except* that instead of asserting what GetMemoryChunkContext asserts,
it should treat those cases as reasons to return false.  So if you
can still do GetMemoryChunkContext then you can still do
MemoryContextContains.  The point of having the separate function
is to be as forgiving as we can of bogus pointers.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-06 03:17  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-09-06 03:17 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 6 Sept 2022 at 14:43, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> I think MemoryContextContains' charter is to return
>
>         GetMemoryChunkContext(pointer) == context
>
> *except* that instead of asserting what GetMemoryChunkContext asserts,
> it should treat those cases as reasons to return false.  So if you
> can still do GetMemoryChunkContext then you can still do
> MemoryContextContains.  The point of having the separate function
> is to be as forgiving as we can of bogus pointers.

Ok.  I've readded the Asserts that c6e0fe1f2 mistakenly removed from
GetMemoryChunkContext() and changed MemoryContextContains() to do
those same pre-checks before calling GetMemoryChunkContext().

I've also boosted the Assert in mcxt.c to
Assert(MemoryContextContains(context, ret)) in each place we call the
context's callback function to obtain a newly allocated pointer.  I
think this should cover the testing.

I felt the need to keep the adjustments I made to the header comment
in MemoryContextContains() to ward off anyone who thinks it's ok to
pass this any random pointer and have it do something sane. It's much
more prone to misbehaving/segfaulting now given the extra dereferences
that c6e0fe1f2 added to obtain a pointer to the owning context.

David

Attachments:

MemoryContextContains_fixes.patch (text/plain, 4.2K) download diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index 64bcc7ef32..3d80abbfae 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -482,6 +482,15 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) MemoryContext GetMemoryChunkContext(void *pointer) { + /* + * Try to detect bogus pointers handed to us, poorly though we can. + * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an + * allocated chunk. + */ + Assert(pointer != NULL); + Assert(pointer == (void *) MAXALIGN(pointer)); + /* adding further Asserts here? See pre-checks in MemoryContextContains */ + return MCXT_METHOD(pointer, get_chunk_context) (pointer); } @@ -809,11 +818,10 @@ MemoryContextCheck(MemoryContext context) * Detect whether an allocated chunk of memory belongs to a given * context or not. * - * Caution: this test is reliable as long as 'pointer' does point to - * a chunk of memory allocated from *some* context. If 'pointer' points - * at memory obtained in some other way, there is a small chance of a - * false-positive result, since the bits right before it might look like - * a valid chunk header by chance. + * Caution: 'pointer' must point to a pointer which was allocated by a + * MemoryContext. It's not safe or valid to use this function on arbitrary + * pointers as obtaining the MemoryContext which 'pointer' belongs to requires + * possibly several pointer dereferences. */ bool MemoryContextContains(MemoryContext context, void *pointer) @@ -821,9 +829,8 @@ MemoryContextContains(MemoryContext context, void *pointer) MemoryContext ptr_context; /* - * NB: Can't use GetMemoryChunkContext() here - that performs assertions - * that aren't acceptable here since we might be passed memory not - * allocated by any memory context. + * NB: We must perform run-time checks here which GetMemoryChunkContext() + * does as assertions before calling GetMemoryChunkContext(). * * Try to detect bogus pointers handed to us, poorly though we can. * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an @@ -835,7 +842,7 @@ MemoryContextContains(MemoryContext context, void *pointer) /* * OK, it's probably safe to look at the context. */ - ptr_context = *(MemoryContext *) (((char *) pointer) - sizeof(void *)); + ptr_context = GetMemoryChunkContext(pointer); return ptr_context == context; } @@ -953,6 +960,8 @@ MemoryContextAlloc(MemoryContext context, Size size) VALGRIND_MEMPOOL_ALLOC(context, ret, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -991,6 +1000,8 @@ MemoryContextAllocZero(MemoryContext context, Size size) MemSetAligned(ret, 0, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1029,6 +1040,8 @@ MemoryContextAllocZeroAligned(MemoryContext context, Size size) MemSetLoop(ret, 0, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1070,6 +1083,8 @@ MemoryContextAllocExtended(MemoryContext context, Size size, int flags) if ((flags & MCXT_ALLOC_ZERO) != 0) MemSetAligned(ret, 0, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1153,6 +1168,8 @@ palloc(Size size) VALGRIND_MEMPOOL_ALLOC(context, ret, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1186,6 +1203,8 @@ palloc0(Size size) MemSetAligned(ret, 0, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1225,6 +1244,8 @@ palloc_extended(Size size, int flags) if ((flags & MCXT_ALLOC_ZERO) != 0) MemSetAligned(ret, 0, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1278,6 +1299,8 @@ repalloc(void *pointer, Size size) VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1313,6 +1336,8 @@ MemoryContextAllocHuge(MemoryContext context, Size size) VALGRIND_MEMPOOL_ALLOC(context, ret, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1352,6 +1377,8 @@ repalloc_huge(void *pointer, Size size) VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size); + Assert(MemoryContextContains(context, ret)); + return ret; }
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-07 04:13  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 2 replies; 152+ messages in thread

From: David Rowley @ 2022-09-07 04:13 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 6 Sept 2022 at 01:41, David Rowley <dgrowleyml@gmail.com> wrote:
>
> On Fri, 2 Sept 2022 at 20:11, David Rowley <dgrowleyml@gmail.com> wrote:
> >
> > On Thu, 1 Sept 2022 at 12:46, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> > >
> > > David Rowley <dgrowleyml@gmail.com> writes:
> > > > Maybe we should just consider always making room for a sentinel for
> > > > chunks that are on dedicated blocks. At most that's an extra 8 bytes
> > > > in some allocation that's either over 1024 or 8192 (depending on
> > > > maxBlockSize).
> > >
> > > Agreed, if we're not doing that already then we should.
> >
> > Here's a patch to that effect.
>
> If there are no objections, then I plan to push that patch soon.

I've now pushed the patch which adds the sentinel space in more cases.

The final analysis I did on the stats gathered during make
installcheck show that we'll now allocate about 19MBs more over the
entire installcheck run out of about 26GBs total allocations.

That analysis looks something like:

Before:

SELECT CASE
         WHEN pow2_size > 0
              AND pow2_size = size THEN 'No'
         WHEN pow2_size = 0
              AND size = maxalign_size THEN 'No'
         ELSE 'Yes'
       END                    AS has_sentinel,
       Count(*)               AS n_allocations,
       Sum(CASE
             WHEN pow2_size > 0 THEN pow2_size
             ELSE maxalign_size
           END) / 1024 / 1024 mega_bytes_alloc
FROM   memstats
GROUP  BY 1;
has_sentinel | n_allocations | mega_bytes_alloc
--------------+---------------+------------------
 No           |      26445855 |            21556
 Yes          |      37602052 |             5044

After:

SELECT CASE
         WHEN pow2_size > 0
              AND pow2_size = size THEN 'No'
         WHEN pow2_size = 0
              AND size = maxalign_size THEN 'Yes' -- this part changed
         ELSE 'Yes'
       END                    AS has_sentinel,
       Count(*)               AS n_allocations,
       Sum(CASE
             WHEN pow2_size > 0 THEN pow2_size
             WHEN size = maxalign_size THEN maxalign_size + 8
             ELSE maxalign_size
           END) / 1024 / 1024 mega_bytes_alloc
FROM   memstats
GROUP  BY 1;
has_sentinel | n_allocations | mega_bytes_alloc
--------------+---------------+------------------
 No           |      23980527 |             2177
 Yes          |      40067380 |            24442

That amounts to previously having about 58.7% of allocations having a
sentinel up to 62.6% currently, during the installcheck run.

It seems a pretty large portion of allocation request sizes are
power-of-2 sized and use AllocSet.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-07 04:56  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 0 replies; 152+ messages in thread

From: Tom Lane @ 2022-09-07 04:56 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> It seems a pretty large portion of allocation request sizes are
> power-of-2 sized and use AllocSet.

No surprise there, we've been programming with aset.c's behavior
in mind for ~20 years ...

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-07 07:15  Yura Sokolov <y.sokolov@postgrespro.ru>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 0 replies; 152+ messages in thread

From: Yura Sokolov @ 2022-09-07 07:15 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tomas Vondra <tomas.vondra@enterprisedb.com>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

В Ср, 07/09/2022 в 16:13 +1200, David Rowley пишет:
> On Tue, 6 Sept 2022 at 01:41, David Rowley <dgrowleyml@gmail.com> wrote:
> > 
> > On Fri, 2 Sept 2022 at 20:11, David Rowley <dgrowleyml@gmail.com> wrote:
> > > 
> > > On Thu, 1 Sept 2022 at 12:46, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> > > > 
> > > > David Rowley <dgrowleyml@gmail.com> writes:
> > > > > Maybe we should just consider always making room for a sentinel for
> > > > > chunks that are on dedicated blocks. At most that's an extra 8 bytes
> > > > > in some allocation that's either over 1024 or 8192 (depending on
> > > > > maxBlockSize).
> > > > 
> > > > Agreed, if we're not doing that already then we should.
> > > 
> > > Here's a patch to that effect.
> > 
> > If there are no objections, then I plan to push that patch soon.
> 
> I've now pushed the patch which adds the sentinel space in more cases.
> 
> The final analysis I did on the stats gathered during make
> installcheck show that we'll now allocate about 19MBs more over the
> entire installcheck run out of about 26GBs total allocations.
> 
> That analysis looks something like:
> 
> Before:
> 
> SELECT CASE
>          WHEN pow2_size > 0
>               AND pow2_size = size THEN 'No'
>          WHEN pow2_size = 0
>               AND size = maxalign_size THEN 'No'
>          ELSE 'Yes'
>        END                    AS has_sentinel,
>        Count(*)               AS n_allocations,
>        Sum(CASE
>              WHEN pow2_size > 0 THEN pow2_size
>              ELSE maxalign_size
>            END) / 1024 / 1024 mega_bytes_alloc
> FROM   memstats
> GROUP  BY 1;
> has_sentinel | n_allocations | mega_bytes_alloc
> --------------+---------------+------------------
>  No           |      26445855 |            21556
>  Yes          |      37602052 |             5044
> 
> After:
> 
> SELECT CASE
>          WHEN pow2_size > 0
>               AND pow2_size = size THEN 'No'
>          WHEN pow2_size = 0
>               AND size = maxalign_size THEN 'Yes' -- this part changed
>          ELSE 'Yes'
>        END                    AS has_sentinel,
>        Count(*)               AS n_allocations,
>        Sum(CASE
>              WHEN pow2_size > 0 THEN pow2_size
>              WHEN size = maxalign_size THEN maxalign_size + 8
>              ELSE maxalign_size
>            END) / 1024 / 1024 mega_bytes_alloc
> FROM   memstats
> GROUP  BY 1;
> has_sentinel | n_allocations | mega_bytes_alloc
> --------------+---------------+------------------
>  No           |      23980527 |             2177
>  Yes          |      40067380 |            24442
> 
> That amounts to previously having about 58.7% of allocations having a
> sentinel up to 62.6% currently, during the installcheck run.
> 
> It seems a pretty large portion of allocation request sizes are
> power-of-2 sized and use AllocSet.

19MB over 26GB is almost nothing. If it is only for enable-casserts
builds, then it is perfectly acceptable.

regards
Yura


^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-07 12:29  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-09-07 12:29 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 6 Sept 2022 at 15:17, David Rowley <dgrowleyml@gmail.com> wrote:
>
> On Tue, 6 Sept 2022 at 14:43, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> > I think MemoryContextContains' charter is to return
> >
> >         GetMemoryChunkContext(pointer) == context
> >
> > *except* that instead of asserting what GetMemoryChunkContext asserts,
> > it should treat those cases as reasons to return false.  So if you
> > can still do GetMemoryChunkContext then you can still do
> > MemoryContextContains.  The point of having the separate function
> > is to be as forgiving as we can of bogus pointers.
>
> Ok.  I've readded the Asserts that c6e0fe1f2 mistakenly removed from
> GetMemoryChunkContext() and changed MemoryContextContains() to do
> those same pre-checks before calling GetMemoryChunkContext().
>
> I've also boosted the Assert in mcxt.c to
> Assert(MemoryContextContains(context, ret)) in each place we call the
> context's callback function to obtain a newly allocated pointer.  I
> think this should cover the testing.
>
> I felt the need to keep the adjustments I made to the header comment
> in MemoryContextContains() to ward off anyone who thinks it's ok to
> pass this any random pointer and have it do something sane. It's much
> more prone to misbehaving/segfaulting now given the extra dereferences
> that c6e0fe1f2 added to obtain a pointer to the owning context.

I spent some time looking at our existing usages of
MemoryContextContains() to satisfy myself that we'll only ever pass in
a pointer to memory allocated by a MemoryContext and pushed this
patch.

I put some notes in the commit message about it being unsafe now to
pass in arbitrary pointers to MemoryContextContains(). Just a note to
the archives that I'd personally feel much better if we just removed
this function in favour of using GetMemoryChunkContext() instead. That
would force extension authors using MemoryContextContains() to rewrite
and revalidate their code. I feel that it's unlikely anyone will
notice until something crashes otherwise. Hopefully that'll happen
before their extension is released.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-07 13:05  Julien Rouhaud <rjuju123@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: Julien Rouhaud @ 2022-09-07 13:05 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Hi,

On Thu, Sep 08, 2022 at 12:29:22AM +1200, David Rowley wrote:
>
> I spent some time looking at our existing usages of
> MemoryContextContains() to satisfy myself that we'll only ever pass in
> a pointer to memory allocated by a MemoryContext and pushed this
> patch.

FYI lapwing isn't happy with this patch:
https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=lapwing&dt=2022-09-07%2012%3A40%3A16.





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-07 13:22  David Rowley <dgrowleyml@gmail.com>
  parent: Julien Rouhaud <rjuju123@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-09-07 13:22 UTC (permalink / raw)
  To: Julien Rouhaud <rjuju123@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Thu, 8 Sept 2022 at 01:05, Julien Rouhaud <rjuju123@gmail.com> wrote:
> FYI lapwing isn't happy with this patch:
> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=lapwing&dt=2022-09-07%2012%3A40%3A16.

Thanks. It does seem to be because of the nodeWindowAgg.c usage of
MemoryContextContains.

I'll look into it further.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-07 13:55  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-09-07 13:55 UTC (permalink / raw)
  To: Julien Rouhaud <rjuju123@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Thu, 8 Sept 2022 at 01:22, David Rowley <dgrowleyml@gmail.com> wrote:
>
> On Thu, 8 Sept 2022 at 01:05, Julien Rouhaud <rjuju123@gmail.com> wrote:
> > FYI lapwing isn't happy with this patch:
> > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=lapwing&dt=2022-09-07%2012%3A40%3A16.
>
> I'll look into it further.

Looks like my analysis wasn't that good in nodeWindowAgg.c.  The
reason it's crashing is due to int2int4_sum() returning
Int64GetDatumFast(transdata->sum).  For 64-bit machines,
Int64GetDatumFast() translates to Int64GetDatum() and and that's
byval, so the MemoryContextContains() call is not triggered, but on
32-bit machines that's PointerGetDatum() and a byref type, and we're
returning a pointer to transdata->sum, which is part way into an
allocation.

Funnily, the struct looks like:

typedef struct Int8TransTypeData
{
int64 count;
int64 sum;
} Int8TransTypeData;

so the previous version of MemoryContextContains() would have
subtracted sizeof(void *) from &transdata->sum which, on this 32-bit
machine would have pointed halfway up the "count" field.  That count
field seems like it would be a good candidate for the "false positive"
that the previous comment in MemoryContextContains mentioned about. So
it looks like it had about a 1 in 2^32 odds of doing the wrong thing
before.

Had the fields in that struct happened to be in the opposite order,
then I don't think it would have crashed, but that's certainly no fix.

I'll need to think about how best to fix this. In the meantime, I
think the other 32-bit animals are probably not going to like this
either :-(

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-07 15:08  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 2 replies; 152+ messages in thread

From: Tom Lane @ 2022-09-07 15:08 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Julien Rouhaud <rjuju123@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> Looks like my analysis wasn't that good in nodeWindowAgg.c.  The
> reason it's crashing is due to int2int4_sum() returning
> Int64GetDatumFast(transdata->sum).

Ugh.  I thought for a bit about whether we could define that as wrong,
but it's returning a portion of its input, which seems kosher enough
(not much different from array subscripting, for instance).

> I'll need to think about how best to fix this. In the meantime, I
> think the other 32-bit animals are probably not going to like this
> either :-(

Yeah.  The basic problem here is that we've greatly reduced the amount
of redundancy in chunk headers.

Perhaps we need to proceed about like this:

1. Check the provided pointer is non-null and maxaligned
(if not, return false).

2. Pull out the mcxt type bits and check that they match the
type of the provided context.

3. If 1 and 2 pass, it's safe enough to call a context-specific
check routine.

4. For aset.c, I'd be inclined to have it compute the AllocBlock
address implied by the putative chunk header, and then run through
the context's alloc blocks and see if any of them match.  If we
do find a match, and the chunk address is within the allocated
length of the block, call it good.  Probably the same could be done
for the other two methods.

Step 4 is annoyingly expensive, but perhaps not too awful given
the way we step up alloc block sizes.  We should make sure that
any context we want to use MemoryContextContains with is allowed
to let its blocks grow large, so that there can't be too many
of them.

I don't see a way to do better if we're afraid to dereference
the computed AllocBlock address.

BTW, if we do it this way, what we'd actually be guaranteeing
is that the address is within some alloc block belonging to
the context; it wouldn't quite prove that the address corresponds
to a currently-allocated chunk.  That'd be good enough probably
for the important use-cases.  In particular it'd be 100% correct
at rejecting chunks of other contexts and chunks gotten from
raw malloc().

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-07 21:32  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-09-07 21:32 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Julien Rouhaud <rjuju123@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Thu, 8 Sept 2022 at 03:08, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> 4. For aset.c, I'd be inclined to have it compute the AllocBlock
> address implied by the putative chunk header, and then run through
> the context's alloc blocks and see if any of them match.  If we
> do find a match, and the chunk address is within the allocated
> length of the block, call it good.  Probably the same could be done
> for the other two methods.
>
> Step 4 is annoyingly expensive, but perhaps not too awful given
> the way we step up alloc block sizes.  We should make sure that
> any context we want to use MemoryContextContains with is allowed
> to let its blocks grow large, so that there can't be too many
> of them.

Thanks for the idea. I've not come up with anything better other than
remove the calls to MemoryContextContains and just copy the Datum each
time.  That doesn't fix the problems with function, however.

I'll go code up your idea and see if doing that triggers any other ideas.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-08 00:13  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 0 replies; 152+ messages in thread

From: David Rowley @ 2022-09-08 00:13 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Julien Rouhaud <rjuju123@gmail.com>; Andres Freund <andres@anarazel.de>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Thu, 8 Sept 2022 at 09:32, David Rowley <dgrowleyml@gmail.com> wrote:
>
> On Thu, 8 Sept 2022 at 03:08, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> > Step 4 is annoyingly expensive, but perhaps not too awful given
> > the way we step up alloc block sizes.  We should make sure that
> > any context we want to use MemoryContextContains with is allowed
> > to let its blocks grow large, so that there can't be too many
> > of them.
>
> I'll go code up your idea and see if doing that triggers any other ideas.

I've attached a very much draft grade patch for this.  I have a couple
of thoughts:

1. I should remove all the Assert(MemoryContextContains(context,
ret)); I littered around mcxt.c. This function is not as cheap as it
once was and I'm expecting that Assert to be a bit too expensive now.
2. I changed the header comment in MemoryContextContains again, but I
removed the part about false positives since I don't believe that is
possible now.  What I do think is just as possible as it was before is
a segfault.  We're still accessing the 8 bytes prior to the given
pointer and there's a decent chance that would segfault when working
with a pointer which was returned by malloc.  I imagine I'm not the
only C programmer around that dislikes writing comments along the
lines of "this might segfault, but..."
3. For external chunks, I'd coded MemoryChunk to put a magic number in
the 60 free bits of the hdrmask.  Since we still need to call
MemoryChunkIsExternal on the given pointer, that function will Assert
that the magic number matches if the external chunk bit is set. We
can't expect that magic number check to pass when the external bit
just happens to be on because it's not a MemoryChunk we're looking at.
For now I commented out those Asserts to make the tests pass. Not sure
what's best there, maybe another version of MemoryChunkIsExternal or
export the underlying macro.  I'm currently more focused on what I
wrote in #2.

David

Attachments:

make_memory_context_contains_more_robust_to_any_pointer.patch (text/plain, 11.5K) download diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index ec423375ae..841d6cda5d 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -1333,6 +1333,46 @@ AllocSetGetChunkContext(void *pointer) return &set->header; } +/* + * AllocSetContains + * Attempt to determine if 'pointer' is memory which was allocated by + * 'context'. Return true if it is, otherwise false. + */ +bool +AllocSetContains(MemoryContext context, void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + AllocBlock block; + AllocSet set = (AllocSet) context; + + /* + * Careful not to dereference anything in 'block' as if 'pointer' is not + * a pointer to an allocated chunk then 'block' could be pointing to about + * anything. + */ + if (MemoryChunkIsExternal(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (AllocBlock) MemoryChunkGetBlock(chunk); + + for (AllocBlock blk = set->blocks; blk != NULL; blk = blk->next) + { + if (block == blk) + { + /* + * The block matches. Now check if 'pointer' falls within the + * block's memory. We don't detect if the pointer is pointing to + * an allocated chunk as that would require looping over the + * freelist for this chunk's size. + */ + if ((char *) pointer >= (char *) blk + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ && + (char *) pointer < blk->endptr) + return true; + } + } + return false; +} + /* * AllocSetGetChunkSpace * Given a currently-allocated chunk, determine the total space diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index c743b24fa7..653fa08064 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -848,6 +848,49 @@ GenerationGetChunkContext(void *pointer) return &block->context->header; } +/* + * GenerationContains + * Attempt to determine if 'pointer' is memory which was allocated by + * 'context'. Return true if it is, otherwise false. + */ +bool +GenerationContains(MemoryContext context, void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationBlock *block; + GenerationContext *set = (GenerationContext *) context; + dlist_iter iter; + + /* + * Careful not to dereference anything in 'block' as if 'pointer' is not + * a pointer to an allocated chunk then 'block' could be pointing to about + * anything. + */ + if (MemoryChunkIsExternal(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (GenerationBlock *) MemoryChunkGetBlock(chunk); + + dlist_foreach(iter, &set->blocks) + { + GenerationBlock *blk = dlist_container(GenerationBlock, node, iter.cur); + + if (block == blk) + { + /* + * The block matches. Now check if 'pointer' falls within the + * block's memory. We don't detect if the pointer is pointing to + * an allocated chunk as that would require looping over the + * freelist for this chunk's size. + */ + if ((char *) pointer >= (char *) blk + Generation_BLOCKHDRSZ + Generation_CHUNKHDRSZ && + (char *) pointer < blk->endptr) + return true; + } + } + return false; +} + /* * GenerationGetChunkSpace * Given a currently-allocated chunk, determine the total space diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index 3d80abbfae..3615a83d53 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -44,6 +44,7 @@ static const MemoryContextMethods mcxt_methods[] = { [MCTX_ASET_ID].reset = AllocSetReset, [MCTX_ASET_ID].delete_context = AllocSetDelete, [MCTX_ASET_ID].get_chunk_context = AllocSetGetChunkContext, + [MCTX_ASET_ID].contains = AllocSetContains, [MCTX_ASET_ID].get_chunk_space = AllocSetGetChunkSpace, [MCTX_ASET_ID].is_empty = AllocSetIsEmpty, [MCTX_ASET_ID].stats = AllocSetStats, @@ -58,6 +59,7 @@ static const MemoryContextMethods mcxt_methods[] = { [MCTX_GENERATION_ID].reset = GenerationReset, [MCTX_GENERATION_ID].delete_context = GenerationDelete, [MCTX_GENERATION_ID].get_chunk_context = GenerationGetChunkContext, + [MCTX_GENERATION_ID].contains = GenerationContains, [MCTX_GENERATION_ID].get_chunk_space = GenerationGetChunkSpace, [MCTX_GENERATION_ID].is_empty = GenerationIsEmpty, [MCTX_GENERATION_ID].stats = GenerationStats, @@ -72,6 +74,7 @@ static const MemoryContextMethods mcxt_methods[] = { [MCTX_SLAB_ID].reset = SlabReset, [MCTX_SLAB_ID].delete_context = SlabDelete, [MCTX_SLAB_ID].get_chunk_context = SlabGetChunkContext, + [MCTX_SLAB_ID].contains = SlabContains, [MCTX_SLAB_ID].get_chunk_space = SlabGetChunkSpace, [MCTX_SLAB_ID].is_empty = SlabIsEmpty, [MCTX_SLAB_ID].stats = SlabStats @@ -818,20 +821,16 @@ MemoryContextCheck(MemoryContext context) * Detect whether an allocated chunk of memory belongs to a given * context or not. * - * Caution: 'pointer' must point to a pointer which was allocated by a - * MemoryContext. It's not safe or valid to use this function on arbitrary - * pointers as obtaining the MemoryContext which 'pointer' belongs to requires - * possibly several pointer dereferences. + * Caution: this test is reliable as long as 'pointer' does point to + * a chunk of memory allocated from *some* context. If 'pointer' points + * at memory obtained in some other way, there is a chance of a segmentation + * violation due to accessing the chunk header, which look for in the 8 bytes + * prior to the pointer. */ bool MemoryContextContains(MemoryContext context, void *pointer) { - MemoryContext ptr_context; - /* - * NB: We must perform run-time checks here which GetMemoryChunkContext() - * does as assertions before calling GetMemoryChunkContext(). - * * Try to detect bogus pointers handed to us, poorly though we can. * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an * allocated chunk. @@ -839,12 +838,10 @@ MemoryContextContains(MemoryContext context, void *pointer) if (pointer == NULL || pointer != (void *) MAXALIGN(pointer)) return false; - /* - * OK, it's probably safe to look at the context. - */ - ptr_context = GetMemoryChunkContext(pointer); + if (GetMemoryChunkMethodID(pointer) != context->method_id) + return false; - return ptr_context == context; + return context->methods->contains(context, pointer); } /* @@ -891,6 +888,8 @@ MemoryContextCreate(MemoryContext node, /* Initialize all standard fields of memory context header */ node->type = tag; + /* Use uint8 to prevent increasing sizeof(MemoryContextData) */ + node->method_id = (uint8) method_id; node->isReset = true; node->methods = &mcxt_methods[method_id]; node->parent = parent; diff --git a/src/backend/utils/mmgr/slab.c b/src/backend/utils/mmgr/slab.c index 9149aaafcb..208c034349 100644 --- a/src/backend/utils/mmgr/slab.c +++ b/src/backend/utils/mmgr/slab.c @@ -567,6 +567,50 @@ SlabGetChunkContext(void *pointer) return &slab->header; } +/* + * SlabContains + * Attempt to determine if 'pointer' is memory which was allocated by + * 'context'. Return true if it is, otherwise false. + */ +bool +SlabContains(MemoryContext context, void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block; + SlabContext *set = (SlabContext *) context; + + /* + * Careful not to dereference anything in 'block' as if 'pointer' is not + * a pointer to an allocated chunk then 'block' could be pointing to about + * anything. + */ + block = (SlabBlock *) MemoryChunkGetBlock(chunk); + + for (int i = 0; i <= set->chunksPerBlock; i++) + { + dlist_iter iter; + + dlist_foreach(iter, &set->freelist[i]) + { + SlabBlock *blk = dlist_container(SlabBlock, node, iter.cur); + + if (block == blk) + { + /* + * The block matches. Now check if 'pointer' falls within the + * block's memory. We don't detect if the pointer is pointing to + * an allocated chunk as that would require looping over the + * freelist for this chunk's size. + */ + if ((char *) pointer >= (char *) blk + Slab_BLOCKHDRSZ + Slab_CHUNKHDRSZ && + (char *) pointer < (char *) blk + set->blockSize) + return true; + } + } + } + return false; +} + /* * SlabGetChunkSpace * Given a currently-allocated chunk, determine the total space diff --git a/src/include/nodes/memnodes.h b/src/include/nodes/memnodes.h index 63d07358cd..6a8d4f4e4e 100644 --- a/src/include/nodes/memnodes.h +++ b/src/include/nodes/memnodes.h @@ -64,6 +64,7 @@ typedef struct MemoryContextMethods void (*reset) (MemoryContext context); void (*delete_context) (MemoryContext context); MemoryContext (*get_chunk_context) (void *pointer); + bool (*contains) (MemoryContext context, void *pointer); Size (*get_chunk_space) (void *pointer); bool (*is_empty) (MemoryContext context); void (*stats) (MemoryContext context, @@ -81,7 +82,8 @@ typedef struct MemoryContextData pg_node_attr(abstract) /* there are no nodes of this type */ NodeTag type; /* identifies exact kind of context */ - /* these two fields are placed here to minimize alignment wastage: */ + /* these three fields are placed here to minimize alignment wastage: */ + uint8 method_id; /* MemoryContextMethodID for this context */ bool isReset; /* T = no space alloced since last reset */ bool allowInCritSection; /* allow palloc in critical section */ Size mem_allocated; /* track memory allocated for this context */ diff --git a/src/include/utils/memutils_internal.h b/src/include/utils/memutils_internal.h index 377cee7a84..ebc1d60393 100644 --- a/src/include/utils/memutils_internal.h +++ b/src/include/utils/memutils_internal.h @@ -25,6 +25,7 @@ extern void *AllocSetRealloc(void *pointer, Size size); extern void AllocSetReset(MemoryContext context); extern void AllocSetDelete(MemoryContext context); extern MemoryContext AllocSetGetChunkContext(void *pointer); +extern bool AllocSetContains(MemoryContext context, void *pointer); extern Size AllocSetGetChunkSpace(void *pointer); extern bool AllocSetIsEmpty(MemoryContext context); extern void AllocSetStats(MemoryContext context, @@ -42,6 +43,7 @@ extern void *GenerationRealloc(void *pointer, Size size); extern void GenerationReset(MemoryContext context); extern void GenerationDelete(MemoryContext context); extern MemoryContext GenerationGetChunkContext(void *pointer); +extern bool GenerationContains(MemoryContext context, void *pointer); extern Size GenerationGetChunkSpace(void *pointer); extern bool GenerationIsEmpty(MemoryContext context); extern void GenerationStats(MemoryContext context, @@ -60,6 +62,7 @@ extern void *SlabRealloc(void *pointer, Size size); extern void SlabReset(MemoryContext context); extern void SlabDelete(MemoryContext context); extern MemoryContext SlabGetChunkContext(void *pointer); +extern bool SlabContains(MemoryContext context, void *pointer); extern Size SlabGetChunkSpace(void *pointer); extern bool SlabIsEmpty(MemoryContext context); extern void SlabStats(MemoryContext context, diff --git a/src/include/utils/memutils_memorychunk.h b/src/include/utils/memutils_memorychunk.h index 2eefc138e3..0e2097250c 100644 --- a/src/include/utils/memutils_memorychunk.h +++ b/src/include/utils/memutils_memorychunk.h @@ -192,8 +192,10 @@ MemoryChunkIsExternal(MemoryChunk *chunk) * External chunks should always store MEMORYCHUNK_MAGIC in the upper * portion of the hdrmask, check that nothing has stomped on that. */ + /* XXX think of what to do here. These will fail if chunk is just a + * arbitrary pointer passed in via MemoryContextContains() Assert(!HdrMaskIsExternal(chunk->hdrmask) || - HdrMaskCheckMagic(chunk->hdrmask)); + HdrMaskCheckMagic(chunk->hdrmask));*/ return HdrMaskIsExternal(chunk->hdrmask); }
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-08 16:44  Andres Freund <andres@anarazel.de>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 1 reply; 152+ messages in thread

From: Andres Freund @ 2022-09-08 16:44 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: David Rowley <dgrowleyml@gmail.com>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2022-09-07 11:08:27 -0400, Tom Lane wrote:
> > I'll need to think about how best to fix this. In the meantime, I
> > think the other 32-bit animals are probably not going to like this
> > either :-(
>
> Yeah.  The basic problem here is that we've greatly reduced the amount
> of redundancy in chunk headers.

Even with the prior amount of redundancy it's quite scary. It's one thing if
the only consequence is a bit of added overhead - but if we *don't* copy the
tuple due to a false positive we're in trouble. Afaict the user would have
some control over the memory contents and so an attacker could work on
triggering this issue. MemoryContextContains() may be ok for an assertion or
such, but relying on it for correctness seems a bad idea.

I wonder if we can get away from needing these checks, without unnecessarily
copying datums every time:

If there is no finalfunc, we know that the tuple ought to be in curaggcontext
or such, and we need to copy.

If there is a finalfunc, they're typically going to return data from within
the current memory context, but could legitimately also return part of the
data from curaggcontext. Perhaps we could forbid that? Our docs already say
the following for serialization funcs:

   The result of the deserialization function should simply be allocated in the
   current memory context, as unlike the combine function's result, it is not
   long-lived.

Perhaps we could institute a similar rule for finalfuncs? The argument against
that is that we can use arbitrary functions as finalfuncs currently. Perhaps
we could treat taking an internal argument as opting into the requirement and
default to copying otherwise?

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-08 18:10  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-09-08 18:10 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: David Rowley <dgrowleyml@gmail.com>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Andres Freund <andres@anarazel.de> writes:
> If there is a finalfunc, they're typically going to return data from within
> the current memory context, but could legitimately also return part of the
> data from curaggcontext. Perhaps we could forbid that?

No, I don't think we can get away with that.  See int8inc() for a
counterexample.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-08 22:15  Andres Freund <andres@anarazel.de>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: Andres Freund @ 2022-09-08 22:15 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: David Rowley <dgrowleyml@gmail.com>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2022-09-08 14:10:36 -0400, Tom Lane wrote:
> Andres Freund <andres@anarazel.de> writes:
> > If there is a finalfunc, they're typically going to return data from within
> > the current memory context, but could legitimately also return part of the
> > data from curaggcontext. Perhaps we could forbid that?
> 
> No, I don't think we can get away with that.  See int8inc() for a
> counterexample.

What I was suggesting a bit below the bit quoted above, was that we'd copy
whenever there's no finalfunc or if the finalfunc doesn't take an internal
parameter. And that finalfuncs returning byref with an internal parameter can
be expected to return memory allocated in the right context (which we of
course could check with an assert).  It's not super satisfying - but I don't
think it'd have the problem you describe above.

Alternatively we could add a column to pg_aggregate denoting this. That'd only
be permissible to set for a superuser presumably.


This business with interpreting random memory as a palloc'd chunk seems like a
fundamentally wrong approach worth incurring some pain to fix.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-08 22:53  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-09-08 22:53 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: David Rowley <dgrowleyml@gmail.com>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Andres Freund <andres@anarazel.de> writes:
> On 2022-09-08 14:10:36 -0400, Tom Lane wrote:
>> No, I don't think we can get away with that.  See int8inc() for a
>> counterexample.

> What I was suggesting a bit below the bit quoted above, was that we'd copy
> whenever there's no finalfunc or if the finalfunc doesn't take an internal
> parameter.

Hmm, OK, I was confusing this with the optimization for transition
functions; but that one is looking for pointer equality rather than
checking MemoryContextContains.  So maybe this'd work.

> This business with interpreting random memory as a palloc'd chunk seems like a
> fundamentally wrong approach worth incurring some pain to fix.

I hate to give up MemoryContextContains altogether.  The assertions
that David nuked in b76fb6c2a had some value I think, and I was hoping
to address your concerns in [1] by adding Assert(MemoryContextContains())
to guc_free.  But I'm not sure how much that'll help to diagnose you-
malloced-instead-of-pallocing if the result is not an assertion failure
but a segfault in a not-obviously-related place.  The failure at guc_free
is already going to be some distance from the scene of the crime.

The implementation I suggested upthread would reliably distinguish
malloc from palloc, and while it is potentially a tad expensive
I don't think it's too much so for Assert checks.  I don't have an
objection to trying to get to a place where we only use it in
Assert, though.

			regards, tom lane

[1] https://www.postgresql.org/message-id/20220905233233.jhcu5jqsrtosmgh5%40awork3.anarazel.de





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-08 23:33  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-09-08 23:33 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Fri, 9 Sept 2022 at 10:53, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> I hate to give up MemoryContextContains altogether.  The assertions
> that David nuked in b76fb6c2a had some value I think,

Those can be put back if we decide to keep MemoryContextContains.
Those newly added Asserts just temporarily had to go due to b76fb6c2a
making MemoryContextContains temporarily always return false.

> The implementation I suggested upthread would reliably distinguish
> malloc from palloc, and while it is potentially a tad expensive
> I don't think it's too much so for Assert checks.  I don't have an
> objection to trying to get to a place where we only use it in
> Assert, though.

I really think the Assert only form of MemoryContextContains() is the
best move, and if it's doing Assert only, then we can do the
loop-over-the-blocks idea as you described and I drafted in [1].

If the need comes up that we're certain we always have a pointer to
some allocated chunk, but need to know if it's in some memory context,
then the proper form of expressing that, I think, should be:

if (GetMemoryChunkContext(pointer) == somecontext)

If we're worried about getting that wrong, we can beef up the
MemoryChunk struct with a magic_number field in
MEMORY_CONTEXT_CHECKING builds to ensure we catch any code which
passes invalid pointers.

David

[1] https://www.postgresql.org/message-id/CAApHDvoKjOmPQeokicwDuO-_Edh=tKp23-=jskYcyKfw5QuDhA@mail.gmail...





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-13 08:27  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-09-13 08:27 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Fri, 9 Sept 2022 at 11:33, David Rowley <dgrowleyml@gmail.com> wrote:
> I really think the Assert only form of MemoryContextContains() is the
> best move, and if it's doing Assert only, then we can do the
> loop-over-the-blocks idea as you described and I drafted in [1].
>
> If the need comes up that we're certain we always have a pointer to
> some allocated chunk, but need to know if it's in some memory context,
> then the proper form of expressing that, I think, should be:
>
> if (GetMemoryChunkContext(pointer) == somecontext)
>
> If we're worried about getting that wrong, we can beef up the
> MemoryChunk struct with a magic_number field in
> MEMORY_CONTEXT_CHECKING builds to ensure we catch any code which
> passes invalid pointers.

I've attached a patch series which is my proposal on what we should do
about MemoryContextContains. In summary, this basically changes
MemoryContextContains() so it's only available in
MEMORY_CONTEXT_CHECKING builds and removes 4 current usages of the
function.

0001: Makes MemoryContextContains work again with the
loop-over-the-blocks method mentioned by Tom.
0002: Adds a new "chunk_magic" field to MemoryChunk.  My thoughts are
that it might be a good idea to do this so that we get Assert failures
if we use functions like GetMemoryChunkContext() on a pointer that's
not a MemoryChunk.
0003: This adjusts aggregate final functions and window functions so
that any byref Datum they return is allocated in CurrentMemoryContext
0004: Makes MemoryContextContains only available in
MEMORY_CONTEXT_CHECKING builds and adjusts our usages of the function
to use GetMemoryChunkContext() instead.

An alternative to 0004, would be more along the lines of what was
mentioned by Andres and just Assert that the returned value is in the
memory context that we expect. I don't think we need to do anything
special with aggregates that take an internal state.  I think the rule
is just as simple as;  all final functions and window functions must
return any byref values in CurrentMemoryContext.  For aggregates
without a finalfn, we can just datumCopy() the returned byref value.
There's no chance for those to be in CurrentMemoryContext anyway. The
return value must be in the aggregate state's context.  The attached
assert.patch shows that this holds true in make check after applying
each of the other patches.

I see that one of the drawbacks from not using MemoryContextContains()
is that window functions such as lead(), lag(), first_value(),
last_value() and nth_value() may now do the datumCopy() when it's not
needed. For example, with a window function call such as
lead(byref_col ), the expression evaluation code in
WinGetFuncArgInPartition() will just return the address in the
tuplestore tuple for "byref_col".  The datumCopy() is needed for that.
However, if the function call was lead(byref_col || 'something') then
we'd have ended up with a new allocation in CurrentMemoryContext to
concatenate the two values.  We'll now do a datumCopy() where we
previously wouldn't have. I don't really see any way around that
without doing some highly invasive surgery to the expression
evaluation code.

None of the attached patches are polished. I can do that once we agree
on the best way to fix the issue.

David

Attachments: download all (5 files, .tar.gz)

v1-0001-Reinstate-MemoryContextContains-to-work-with-arbi.patch (text/plain, 15.3K) download From a9fcf078bc8a87742860abee527199f772f39f5b Mon Sep 17 00:00:00 2001 From: David Rowley <dgrowley@gmail.com> Date: Thu, 8 Sep 2022 23:32:03 +1200 Subject: [PATCH v1 1/4] Reinstate MemoryContextContains to work with arbitrary pointers --- src/backend/utils/mmgr/aset.c | 42 ++++++++++++++++++ src/backend/utils/mmgr/generation.c | 45 +++++++++++++++++++ src/backend/utils/mmgr/mcxt.c | 56 ++++++++++++++---------- src/backend/utils/mmgr/slab.c | 44 +++++++++++++++++++ src/include/nodes/memnodes.h | 4 +- src/include/utils/memutils_internal.h | 3 ++ src/include/utils/memutils_memorychunk.h | 21 +++++++++ 7 files changed, 191 insertions(+), 24 deletions(-) diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index ec423375ae..24ab7399a3 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -1333,6 +1333,48 @@ AllocSetGetChunkContext(void *pointer) return &set->header; } +/* + * AllocSetContains + * Attempt to determine if 'pointer' is memory which was allocated by + * 'context'. Return true if it is, otherwise false. + */ +bool +AllocSetContains(MemoryContext context, void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + AllocBlock block; + AllocSet set = (AllocSet) context; + + /* + * We must use MemoryChunkIsExternalUnSafePointer() instead of + * MemoryChunkIsExternal() here as 'chunk' may not be a MemoryChunk if + * 'pointer' is not pointing to palloced memory. Below we're careful + * never to dereference 'block' as it could point to memory not owned by + * this process. + */ + if (MemoryChunkIsExternalUnSafePointer(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (AllocBlock) MemoryChunkGetBlock(chunk); + + for (AllocBlock blk = set->blocks; blk != NULL; blk = blk->next) + { + if (block == blk) + { + /* + * The block matches. Now check if 'pointer' falls within the + * block's memory. We don't detect if the pointer is pointing to + * an allocated chunk as that would require looping over the + * freelist for this chunk's size. + */ + if ((char *) pointer >= (char *) blk + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ && + (char *) pointer < blk->endptr) + return true; + } + } + return false; +} + /* * AllocSetGetChunkSpace * Given a currently-allocated chunk, determine the total space diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index c743b24fa7..212aba6bf3 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -848,6 +848,51 @@ GenerationGetChunkContext(void *pointer) return &block->context->header; } +/* + * GenerationContains + * Attempt to determine if 'pointer' is memory which was allocated by + * 'context'. Return true if it is, otherwise false. + */ +bool +GenerationContains(MemoryContext context, void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + GenerationBlock *block; + GenerationContext *set = (GenerationContext *) context; + dlist_iter iter; + + /* + * We must use MemoryChunkIsExternalUnSafePointer() instead of + * MemoryChunkIsExternal() here as 'chunk' may not be a MemoryChunk if + * 'pointer' is not pointing to palloced memory. Below we're careful + * never to dereference 'block' as it could point to memory not owned by + * this process. + */ + if (MemoryChunkIsExternalUnSafePointer(chunk)) + block = ExternalChunkGetBlock(chunk); + else + block = (GenerationBlock *) MemoryChunkGetBlock(chunk); + + dlist_foreach(iter, &set->blocks) + { + GenerationBlock *blk = dlist_container(GenerationBlock, node, iter.cur); + + if (block == blk) + { + /* + * The block matches. Now check if 'pointer' falls within the + * block's memory. We don't detect if the pointer is pointing to + * an allocated chunk as that would require looping over the + * freelist for this chunk's size. + */ + if ((char *) pointer >= (char *) blk + Generation_BLOCKHDRSZ + Generation_CHUNKHDRSZ && + (char *) pointer < blk->endptr) + return true; + } + } + return false; +} + /* * GenerationGetChunkSpace * Given a currently-allocated chunk, determine the total space diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index 115a64cfe4..3615a83d53 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -44,6 +44,7 @@ static const MemoryContextMethods mcxt_methods[] = { [MCTX_ASET_ID].reset = AllocSetReset, [MCTX_ASET_ID].delete_context = AllocSetDelete, [MCTX_ASET_ID].get_chunk_context = AllocSetGetChunkContext, + [MCTX_ASET_ID].contains = AllocSetContains, [MCTX_ASET_ID].get_chunk_space = AllocSetGetChunkSpace, [MCTX_ASET_ID].is_empty = AllocSetIsEmpty, [MCTX_ASET_ID].stats = AllocSetStats, @@ -58,6 +59,7 @@ static const MemoryContextMethods mcxt_methods[] = { [MCTX_GENERATION_ID].reset = GenerationReset, [MCTX_GENERATION_ID].delete_context = GenerationDelete, [MCTX_GENERATION_ID].get_chunk_context = GenerationGetChunkContext, + [MCTX_GENERATION_ID].contains = GenerationContains, [MCTX_GENERATION_ID].get_chunk_space = GenerationGetChunkSpace, [MCTX_GENERATION_ID].is_empty = GenerationIsEmpty, [MCTX_GENERATION_ID].stats = GenerationStats, @@ -72,6 +74,7 @@ static const MemoryContextMethods mcxt_methods[] = { [MCTX_SLAB_ID].reset = SlabReset, [MCTX_SLAB_ID].delete_context = SlabDelete, [MCTX_SLAB_ID].get_chunk_context = SlabGetChunkContext, + [MCTX_SLAB_ID].contains = SlabContains, [MCTX_SLAB_ID].get_chunk_space = SlabGetChunkSpace, [MCTX_SLAB_ID].is_empty = SlabIsEmpty, [MCTX_SLAB_ID].stats = SlabStats @@ -818,28 +821,16 @@ MemoryContextCheck(MemoryContext context) * Detect whether an allocated chunk of memory belongs to a given * context or not. * - * Caution: 'pointer' must point to a pointer which was allocated by a - * MemoryContext. It's not safe or valid to use this function on arbitrary - * pointers as obtaining the MemoryContext which 'pointer' belongs to requires - * possibly several pointer dereferences. + * Caution: this test is reliable as long as 'pointer' does point to + * a chunk of memory allocated from *some* context. If 'pointer' points + * at memory obtained in some other way, there is a chance of a segmentation + * violation due to accessing the chunk header, which look for in the 8 bytes + * prior to the pointer. */ bool MemoryContextContains(MemoryContext context, void *pointer) { /* - * Temporarily make this always return false as we don't yet have a fully - * baked idea on how to make it work correctly with the new MemoryChunk - * code. - */ - return false; - -#ifdef NOT_USED - MemoryContext ptr_context; - - /* - * NB: We must perform run-time checks here which GetMemoryChunkContext() - * does as assertions before calling GetMemoryChunkContext(). - * * Try to detect bogus pointers handed to us, poorly though we can. * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an * allocated chunk. @@ -847,13 +838,10 @@ MemoryContextContains(MemoryContext context, void *pointer) if (pointer == NULL || pointer != (void *) MAXALIGN(pointer)) return false; - /* - * OK, it's probably safe to look at the context. - */ - ptr_context = GetMemoryChunkContext(pointer); + if (GetMemoryChunkMethodID(pointer) != context->method_id) + return false; - return ptr_context == context; -#endif + return context->methods->contains(context, pointer); } /* @@ -900,6 +888,8 @@ MemoryContextCreate(MemoryContext node, /* Initialize all standard fields of memory context header */ node->type = tag; + /* Use uint8 to prevent increasing sizeof(MemoryContextData) */ + node->method_id = (uint8) method_id; node->isReset = true; node->methods = &mcxt_methods[method_id]; node->parent = parent; @@ -969,6 +959,8 @@ MemoryContextAlloc(MemoryContext context, Size size) VALGRIND_MEMPOOL_ALLOC(context, ret, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1007,6 +999,8 @@ MemoryContextAllocZero(MemoryContext context, Size size) MemSetAligned(ret, 0, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1045,6 +1039,8 @@ MemoryContextAllocZeroAligned(MemoryContext context, Size size) MemSetLoop(ret, 0, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1086,6 +1082,8 @@ MemoryContextAllocExtended(MemoryContext context, Size size, int flags) if ((flags & MCXT_ALLOC_ZERO) != 0) MemSetAligned(ret, 0, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1169,6 +1167,8 @@ palloc(Size size) VALGRIND_MEMPOOL_ALLOC(context, ret, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1202,6 +1202,8 @@ palloc0(Size size) MemSetAligned(ret, 0, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1241,6 +1243,8 @@ palloc_extended(Size size, int flags) if ((flags & MCXT_ALLOC_ZERO) != 0) MemSetAligned(ret, 0, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1294,6 +1298,8 @@ repalloc(void *pointer, Size size) VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1329,6 +1335,8 @@ MemoryContextAllocHuge(MemoryContext context, Size size) VALGRIND_MEMPOOL_ALLOC(context, ret, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1368,6 +1376,8 @@ repalloc_huge(void *pointer, Size size) VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size); + Assert(MemoryContextContains(context, ret)); + return ret; } diff --git a/src/backend/utils/mmgr/slab.c b/src/backend/utils/mmgr/slab.c index 9149aaafcb..b5c801eb01 100644 --- a/src/backend/utils/mmgr/slab.c +++ b/src/backend/utils/mmgr/slab.c @@ -567,6 +567,50 @@ SlabGetChunkContext(void *pointer) return &slab->header; } +/* + * SlabContains + * Attempt to determine if 'pointer' is memory which was allocated by + * 'context'. Return true if it is, otherwise false. + */ +bool +SlabContains(MemoryContext context, void *pointer) +{ + MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + SlabBlock *block; + SlabContext *set = (SlabContext *) context; + + /* + * Careful not to dereference anything in 'block' as if 'pointer' is not a + * pointer to an allocated chunk then 'block' could be pointing to about + * anything. + */ + block = (SlabBlock *) MemoryChunkGetBlock(chunk); + + for (int i = 0; i <= set->chunksPerBlock; i++) + { + dlist_iter iter; + + dlist_foreach(iter, &set->freelist[i]) + { + SlabBlock *blk = dlist_container(SlabBlock, node, iter.cur); + + if (block == blk) + { + /* + * The block matches. Now check if 'pointer' falls within the + * block's memory. We don't detect if the pointer is pointing + * to an allocated chunk as that would require looping over + * the freelist for this chunk's size. + */ + if ((char *) pointer >= (char *) blk + Slab_BLOCKHDRSZ + Slab_CHUNKHDRSZ && + (char *) pointer < (char *) blk + set->blockSize) + return true; + } + } + } + return false; +} + /* * SlabGetChunkSpace * Given a currently-allocated chunk, determine the total space diff --git a/src/include/nodes/memnodes.h b/src/include/nodes/memnodes.h index 63d07358cd..6a8d4f4e4e 100644 --- a/src/include/nodes/memnodes.h +++ b/src/include/nodes/memnodes.h @@ -64,6 +64,7 @@ typedef struct MemoryContextMethods void (*reset) (MemoryContext context); void (*delete_context) (MemoryContext context); MemoryContext (*get_chunk_context) (void *pointer); + bool (*contains) (MemoryContext context, void *pointer); Size (*get_chunk_space) (void *pointer); bool (*is_empty) (MemoryContext context); void (*stats) (MemoryContext context, @@ -81,7 +82,8 @@ typedef struct MemoryContextData pg_node_attr(abstract) /* there are no nodes of this type */ NodeTag type; /* identifies exact kind of context */ - /* these two fields are placed here to minimize alignment wastage: */ + /* these three fields are placed here to minimize alignment wastage: */ + uint8 method_id; /* MemoryContextMethodID for this context */ bool isReset; /* T = no space alloced since last reset */ bool allowInCritSection; /* allow palloc in critical section */ Size mem_allocated; /* track memory allocated for this context */ diff --git a/src/include/utils/memutils_internal.h b/src/include/utils/memutils_internal.h index 377cee7a84..ebc1d60393 100644 --- a/src/include/utils/memutils_internal.h +++ b/src/include/utils/memutils_internal.h @@ -25,6 +25,7 @@ extern void *AllocSetRealloc(void *pointer, Size size); extern void AllocSetReset(MemoryContext context); extern void AllocSetDelete(MemoryContext context); extern MemoryContext AllocSetGetChunkContext(void *pointer); +extern bool AllocSetContains(MemoryContext context, void *pointer); extern Size AllocSetGetChunkSpace(void *pointer); extern bool AllocSetIsEmpty(MemoryContext context); extern void AllocSetStats(MemoryContext context, @@ -42,6 +43,7 @@ extern void *GenerationRealloc(void *pointer, Size size); extern void GenerationReset(MemoryContext context); extern void GenerationDelete(MemoryContext context); extern MemoryContext GenerationGetChunkContext(void *pointer); +extern bool GenerationContains(MemoryContext context, void *pointer); extern Size GenerationGetChunkSpace(void *pointer); extern bool GenerationIsEmpty(MemoryContext context); extern void GenerationStats(MemoryContext context, @@ -60,6 +62,7 @@ extern void *SlabRealloc(void *pointer, Size size); extern void SlabReset(MemoryContext context); extern void SlabDelete(MemoryContext context); extern MemoryContext SlabGetChunkContext(void *pointer); +extern bool SlabContains(MemoryContext context, void *pointer); extern Size SlabGetChunkSpace(void *pointer); extern bool SlabIsEmpty(MemoryContext context); extern void SlabStats(MemoryContext context, diff --git a/src/include/utils/memutils_memorychunk.h b/src/include/utils/memutils_memorychunk.h index 2eefc138e3..721c7d004c 100644 --- a/src/include/utils/memutils_memorychunk.h +++ b/src/include/utils/memutils_memorychunk.h @@ -54,6 +54,12 @@ * Determine if the given MemoryChunk is externally managed, i.e. * MemoryChunkSetHdrMaskExternal() was called on the chunk. * + * MemoryChunkIsExternalUnSafePointer: + * As MemoryChunkIsExternal but safe to use on pointers that we're + * uncertain are pointers to MemoryChunks. Callers must be careful + * not to put too much trust into the return value. The primary usecase + * for this is to implement MemoryContextContains. + * * MemoryChunkGetValue: * For non-external chunks, return the stored 30-bit value as it was set * in the call to MemoryChunkSetHdrMask(). @@ -198,6 +204,21 @@ MemoryChunkIsExternal(MemoryChunk *chunk) return HdrMaskIsExternal(chunk->hdrmask); } +/* + * MemoryChunkIsExternalUnSafePointer + * As MemoryChunkIsExternal only without any Assert checking. This + * version should only be used when we're uncertain of 'chunk' is + * actually a pointer to a MemoryChunk. + * + * Note: Callers must be careful not to put too much trust into the return + * value as 'chunk' may not be a MemoryChunk. + */ +static inline bool +MemoryChunkIsExternalUnSafePointer(MemoryChunk *chunk) +{ + return HdrMaskIsExternal(chunk->hdrmask); +} + /* * MemoryChunkGetValue * For non-external chunks, returns the value field as it was set in -- 2.34.1
v1-0002-Add-a-magic-number-to-all-MemoryChunks-and-verify.patch (text/plain, 7.1K) download From 1de691bf2421c3c87fc513f4c2155f140d21e2c0 Mon Sep 17 00:00:00 2001 From: David Rowley <dgrowley@gmail.com> Date: Fri, 9 Sep 2022 13:11:32 +1200 Subject: [PATCH v1 2/4] Add a magic number to all MemoryChunks and verify We only do this for MEMORY_CONTEXT_CHECKING builds. The aim here is to give us more confidence that we're dealing with chunks allocated by a MemoryContext in various cases where there's a chance that we might not be. --- src/backend/utils/mmgr/aset.c | 6 +-- src/backend/utils/mmgr/generation.c | 6 +-- src/include/utils/memutils_memorychunk.h | 48 ++++++++++++++++++++++-- 3 files changed, 51 insertions(+), 9 deletions(-) diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index 24ab7399a3..b435624d8f 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -1346,16 +1346,16 @@ AllocSetContains(MemoryContext context, void *pointer) AllocSet set = (AllocSet) context; /* - * We must use MemoryChunkIsExternalUnSafePointer() instead of + * We must use MemoryChunkIsExternalUnsafePointer() instead of * MemoryChunkIsExternal() here as 'chunk' may not be a MemoryChunk if * 'pointer' is not pointing to palloced memory. Below we're careful * never to dereference 'block' as it could point to memory not owned by * this process. */ - if (MemoryChunkIsExternalUnSafePointer(chunk)) + if (MemoryChunkIsExternalUnsafePointer(chunk)) block = ExternalChunkGetBlock(chunk); else - block = (AllocBlock) MemoryChunkGetBlock(chunk); + block = (AllocBlock) MemoryChunkGetBlockUnsafePointer(chunk); for (AllocBlock blk = set->blocks; blk != NULL; blk = blk->next) { diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index 212aba6bf3..f6a3a01912 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -862,16 +862,16 @@ GenerationContains(MemoryContext context, void *pointer) dlist_iter iter; /* - * We must use MemoryChunkIsExternalUnSafePointer() instead of + * We must use MemoryChunkIsExternalUnsafePointer() instead of * MemoryChunkIsExternal() here as 'chunk' may not be a MemoryChunk if * 'pointer' is not pointing to palloced memory. Below we're careful * never to dereference 'block' as it could point to memory not owned by * this process. */ - if (MemoryChunkIsExternalUnSafePointer(chunk)) + if (MemoryChunkIsExternalUnsafePointer(chunk)) block = ExternalChunkGetBlock(chunk); else - block = (GenerationBlock *) MemoryChunkGetBlock(chunk); + block = (GenerationBlock *) MemoryChunkGetBlockUnsafePointer(chunk); dlist_foreach(iter, &set->blocks) { diff --git a/src/include/utils/memutils_memorychunk.h b/src/include/utils/memutils_memorychunk.h index 721c7d004c..9b267e9ce4 100644 --- a/src/include/utils/memutils_memorychunk.h +++ b/src/include/utils/memutils_memorychunk.h @@ -54,7 +54,7 @@ * Determine if the given MemoryChunk is externally managed, i.e. * MemoryChunkSetHdrMaskExternal() was called on the chunk. * - * MemoryChunkIsExternalUnSafePointer: + * MemoryChunkIsExternalUnsafePointer: * As MemoryChunkIsExternal but safe to use on pointers that we're * uncertain are pointers to MemoryChunks. Callers must be careful * not to put too much trust into the return value. The primary usecase @@ -68,6 +68,12 @@ * For non-external chunks, return a pointer to the block as it was set * in the call to MemoryChunkSetHdrMask(). * + * MemoryChunkGetBlockUnsafePointer: + * As MemoryChunkGetBlock but safe to use on pointers that we're + * uncertain are pointers to MemoryChunks. Callers must be careful + * not to put too much trust into the return value. The primary usecase + * for this is to implement MemoryContextContains. + * * Also exports: * MEMORYCHUNK_MAX_VALUE * MEMORYCHUNK_MAX_BLOCKOFFSET @@ -113,9 +119,18 @@ MEMORYCHUNK_VALUE_BASEBIT << \ MEMORYCHUNK_VALUE_BASEBIT) +#ifdef MEMORY_CONTEXT_CHECKING +#if SIZEOF_SIZE_T >= 8 +#define MEMORYCHUNK_MAGIC2 UINT64CONST(0xB1A8DB858EB6EFBA) +#else +#define MEMORYCHUNK_MAGIC2 0x8EB6EFBA +#endif +#endif + typedef struct MemoryChunk { #ifdef MEMORY_CONTEXT_CHECKING + Size chunk_magic; /* magic number */ Size requested_size; #endif @@ -167,6 +182,9 @@ MemoryChunkSetHdrMask(MemoryChunk *chunk, void *block, Assert(value <= MEMORYCHUNK_MAX_VALUE); Assert((int) methodid <= MEMORY_CONTEXT_METHODID_MASK); +#ifdef MEMORY_CONTEXT_CHECKING + chunk->chunk_magic = MEMORYCHUNK_MAGIC2; +#endif chunk->hdrmask = (((uint64) blockoffset) << MEMORYCHUNK_BLOCKOFFSET_BASEBIT) | (((uint64) value) << MEMORYCHUNK_VALUE_BASEBIT) | methodid; @@ -183,6 +201,9 @@ MemoryChunkSetHdrMaskExternal(MemoryChunk *chunk, { Assert((int) methodid <= MEMORY_CONTEXT_METHODID_MASK); +#ifdef MEMORY_CONTEXT_CHECKING + chunk->chunk_magic = MEMORYCHUNK_MAGIC2; +#endif chunk->hdrmask = MEMORYCHUNK_MAGIC | (((uint64) 1) << MEMORYCHUNK_EXTERNAL_BASEBIT) | methodid; } @@ -200,12 +221,13 @@ MemoryChunkIsExternal(MemoryChunk *chunk) */ Assert(!HdrMaskIsExternal(chunk->hdrmask) || HdrMaskCheckMagic(chunk->hdrmask)); + Assert(chunk->chunk_magic == MEMORYCHUNK_MAGIC2); return HdrMaskIsExternal(chunk->hdrmask); } /* - * MemoryChunkIsExternalUnSafePointer + * MemoryChunkIsExternalUnsafePointer * As MemoryChunkIsExternal only without any Assert checking. This * version should only be used when we're uncertain of 'chunk' is * actually a pointer to a MemoryChunk. @@ -214,7 +236,7 @@ MemoryChunkIsExternal(MemoryChunk *chunk) * value as 'chunk' may not be a MemoryChunk. */ static inline bool -MemoryChunkIsExternalUnSafePointer(MemoryChunk *chunk) +MemoryChunkIsExternalUnsafePointer(MemoryChunk *chunk) { return HdrMaskIsExternal(chunk->hdrmask); } @@ -228,6 +250,7 @@ static inline Size MemoryChunkGetValue(MemoryChunk *chunk) { Assert(!HdrMaskIsExternal(chunk->hdrmask)); + Assert(chunk->chunk_magic == MEMORYCHUNK_MAGIC2); return HdrMaskGetValue(chunk->hdrmask); } @@ -241,15 +264,34 @@ static inline void * MemoryChunkGetBlock(MemoryChunk *chunk) { Assert(!HdrMaskIsExternal(chunk->hdrmask)); + Assert(chunk->chunk_magic == MEMORYCHUNK_MAGIC2); return (void *) ((char *) chunk - HdrMaskBlockOffset(chunk->hdrmask)); } +/* + * MemoryChunkGetBlockUnsafePointer + * For non-external chunks, returns the pointer to the block as was set + * in MemoryChunkSetHdrMask. This differs from MemoryChunkGetBlock as + * the coding here does not assume 'chunk' is a valid MemoryChunk. + * We so still assume that the caller checked if the external bit was not + * set with MemoryChunkIsExternalUnsafePointer. + */ +static inline void * +MemoryChunkGetBlockUnsafePointer(MemoryChunk *chunk) +{ + Assert(!HdrMaskIsExternal(chunk->hdrmask)); + + return (void *) ((char *) chunk - HdrMaskBlockOffset(chunk->hdrmask)); +} + + /* cleanup all internal definitions */ #undef MEMORYCHUNK_EXTERNAL_BASEBIT #undef MEMORYCHUNK_VALUE_BASEBIT #undef MEMORYCHUNK_BLOCKOFFSET_BASEBIT #undef MEMORYCHUNK_MAGIC +#undef MEMORYCHUNK_MAGIC2 #undef HdrMaskIsExternal #undef HdrMaskGetValue #undef HdrMaskBlockOffset -- 2.34.1
v1-0003-Adjust-memory-context-API-with-aggregate-and-wind.patch (text/plain, 6.3K) download From 1a1d69334b9cbecca5038528bc7a5bddcc5f05ca Mon Sep 17 00:00:00 2001 From: David Rowley <dgrowley@gmail.com> Date: Fri, 9 Sep 2022 13:16:46 +1200 Subject: [PATCH v1 3/4] Adjust memory context API with aggregate and window functions This makes it so an aggregate function's final function always returns any byref types in memory allocated in CurrentMemoryContext. The same is also done here for window functions. A window function may now call the PG_WINDOW_RESULTINFO() macro to obtain a WindowResultInfo in order to determine the result type details of the return value. Functions which do not currently return in CurrentMemoryContext must perform a datumCopy(). Extension authors who have created aggregates with a final function or created their own window functions must ensure their C code conforms. --- src/backend/executor/nodeWindowAgg.c | 10 +++++++--- src/backend/utils/adt/numeric.c | 2 +- src/backend/utils/adt/windowfuncs.c | 21 +++++++++++++++++++++ src/include/windowapi.h | 12 ++++++++++++ 4 files changed, 41 insertions(+), 4 deletions(-) diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c index 8b0858e9f5..ba119046f4 100644 --- a/src/backend/executor/nodeWindowAgg.c +++ b/src/backend/executor/nodeWindowAgg.c @@ -1034,9 +1034,13 @@ eval_windowfunction(WindowAggState *winstate, WindowStatePerFunc perfuncstate, { LOCAL_FCINFO(fcinfo, FUNC_MAX_ARGS); MemoryContext oldContext; + WindowResultInfo resultinfo; oldContext = MemoryContextSwitchTo(winstate->ss.ps.ps_ExprContext->ecxt_per_tuple_memory); + resultinfo.resulttypeLen = perfuncstate->resulttypeLen; + resultinfo.resulttypeByVal = perfuncstate->resulttypeByVal; + /* * We don't pass any normal arguments to a window function, but we do pass * it the number of arguments, in order to permit window function @@ -1046,7 +1050,8 @@ eval_windowfunction(WindowAggState *winstate, WindowStatePerFunc perfuncstate, InitFunctionCallInfoData(*fcinfo, &(perfuncstate->flinfo), perfuncstate->numArguments, perfuncstate->winCollation, - (void *) perfuncstate->winobj, NULL); + (void *) perfuncstate->winobj, + (void *) &resultinfo); /* Just in case, make all the regular argument slots be null */ for (int argno = 0; argno < perfuncstate->numArguments; argno++) fcinfo->args[argno].isnull = true; @@ -1062,8 +1067,7 @@ eval_windowfunction(WindowAggState *winstate, WindowStatePerFunc perfuncstate, * tuple, as is entirely possible.) */ if (!perfuncstate->resulttypeByVal && !fcinfo->isnull && - !MemoryContextContains(CurrentMemoryContext, - DatumGetPointer(*result))) + GetMemoryChunkContext(DatumGetPointer(*result)) != CurrentMemoryContext) *result = datumCopy(*result, perfuncstate->resulttypeByVal, perfuncstate->resulttypeLen); diff --git a/src/backend/utils/adt/numeric.c b/src/backend/utils/adt/numeric.c index 920a63b008..2ac7de70c5 100644 --- a/src/backend/utils/adt/numeric.c +++ b/src/backend/utils/adt/numeric.c @@ -6643,7 +6643,7 @@ int2int4_sum(PG_FUNCTION_ARGS) if (transdata->count == 0) PG_RETURN_NULL(); - PG_RETURN_DATUM(Int64GetDatumFast(transdata->sum)); + PG_RETURN_DATUM(Int64GetDatum(transdata->sum)); } diff --git a/src/backend/utils/adt/windowfuncs.c b/src/backend/utils/adt/windowfuncs.c index 596564fa15..40f0a08123 100644 --- a/src/backend/utils/adt/windowfuncs.c +++ b/src/backend/utils/adt/windowfuncs.c @@ -15,6 +15,7 @@ #include "nodes/supportnodes.h" #include "utils/builtins.h" +#include "utils/datum.h" #include "windowapi.h" /* @@ -350,6 +351,7 @@ leadlag_common(FunctionCallInfo fcinfo, bool forward, bool withoffset, bool withdefault) { WindowObject winobj = PG_WINDOW_OBJECT(); + WindowResultInfo *wresinfo = PG_WINDOW_RESULTINFO(); int32 offset; bool const_offset; Datum result; @@ -388,6 +390,10 @@ leadlag_common(FunctionCallInfo fcinfo, if (isnull) PG_RETURN_NULL(); + if (!wresinfo->resulttypeByVal) + result = datumCopy(result, wresinfo->resulttypeByVal, + wresinfo->resulttypeLen); + PG_RETURN_DATUM(result); } @@ -470,6 +476,7 @@ Datum window_first_value(PG_FUNCTION_ARGS) { WindowObject winobj = PG_WINDOW_OBJECT(); + WindowResultInfo *wresinfo = PG_WINDOW_RESULTINFO(); Datum result; bool isnull; @@ -479,6 +486,10 @@ window_first_value(PG_FUNCTION_ARGS) if (isnull) PG_RETURN_NULL(); + if (!wresinfo->resulttypeByVal) + result = datumCopy(result, wresinfo->resulttypeByVal, + wresinfo->resulttypeLen); + PG_RETURN_DATUM(result); } @@ -491,6 +502,7 @@ Datum window_last_value(PG_FUNCTION_ARGS) { WindowObject winobj = PG_WINDOW_OBJECT(); + WindowResultInfo *wresinfo = PG_WINDOW_RESULTINFO(); Datum result; bool isnull; @@ -500,6 +512,10 @@ window_last_value(PG_FUNCTION_ARGS) if (isnull) PG_RETURN_NULL(); + if (!wresinfo->resulttypeByVal) + result = datumCopy(result, wresinfo->resulttypeByVal, + wresinfo->resulttypeLen); + PG_RETURN_DATUM(result); } @@ -512,6 +528,7 @@ Datum window_nth_value(PG_FUNCTION_ARGS) { WindowObject winobj = PG_WINDOW_OBJECT(); + WindowResultInfo *wresinfo = PG_WINDOW_RESULTINFO(); bool const_offset; Datum result; bool isnull; @@ -533,5 +550,9 @@ window_nth_value(PG_FUNCTION_ARGS) if (isnull) PG_RETURN_NULL(); + if (!wresinfo->resulttypeByVal) + result = datumCopy(result, wresinfo->resulttypeByVal, + wresinfo->resulttypeLen); + PG_RETURN_DATUM(result); } diff --git a/src/include/windowapi.h b/src/include/windowapi.h index 5a620a2e42..c3d65b161c 100644 --- a/src/include/windowapi.h +++ b/src/include/windowapi.h @@ -36,7 +36,19 @@ /* this struct is private in nodeWindowAgg.c */ typedef struct WindowObjectData *WindowObject; +/* + * Evaluation of window functions are passed this object and it's available + * via fcinfo->resultinfo and can be accessed in the window function via the + * PG_WINDOW_RESULTINFO macro. + */ +typedef struct WindowResultInfo +{ + int16 resulttypeLen; /* type length of wfunc's result type */ + bool resulttypeByVal; /* true if wfunc's result is byval */ +} WindowResultInfo; + #define PG_WINDOW_OBJECT() ((WindowObject) fcinfo->context) +#define PG_WINDOW_RESULTINFO() ((WindowResultInfo *) fcinfo->resultinfo) #define WindowObjectIsValid(winobj) \ ((winobj) != NULL && IsA(winobj, WindowObjectData)) -- 2.34.1
v1-0004-Demote-MemoryContextContains-to-MEMORY_CONTEXT_CH.patch (text/plain, 10.9K) download From 28f287cdd32f4d3bdde0fd803c9357646e904a17 Mon Sep 17 00:00:00 2001 From: David Rowley <dgrowley@gmail.com> Date: Fri, 9 Sep 2022 16:19:13 +1200 Subject: [PATCH v1 4/4] Demote MemoryContextContains to MEMORY_CONTEXT_CHECKING builds only Making MemoryContextContains work like it did prior to c6e0fe1f2 required making it perform a loop over each block that the MemoryContext had allocated and check if the pointer is in the address-space range of that block. This was far too expensive to be used as a general-purpose function. Here we instead opt to use GetMemoryChunkContext(). Previously we couldn't use that function as it only works when given a pointer as it was returned by palloc and co. For some use cases of MemoryContextContains they could receive a pointer into a tuple (as was the case for lead/lag window functions, and a pointer to a field in an internal aggregate state, as was the case for int2int4_sum(). --- src/backend/executor/nodeAgg.c | 6 ++---- src/backend/executor/nodeWindowAgg.c | 3 +-- src/backend/utils/mmgr/aset.c | 2 ++ src/backend/utils/mmgr/generation.c | 3 +++ src/backend/utils/mmgr/mcxt.c | 10 ++++++---- src/backend/utils/mmgr/slab.c | 2 ++ src/include/nodes/memnodes.h | 2 +- src/include/utils/memutils.h | 2 +- src/include/utils/memutils_internal.h | 6 +++--- 9 files changed, 21 insertions(+), 15 deletions(-) diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c index 933c304901..323ae94938 100644 --- a/src/backend/executor/nodeAgg.c +++ b/src/backend/executor/nodeAgg.c @@ -1122,8 +1122,7 @@ finalize_aggregate(AggState *aggstate, * If result is pass-by-ref, make sure it is in the right context. */ if (!peragg->resulttypeByVal && !*resultIsNull && - !MemoryContextContains(CurrentMemoryContext, - DatumGetPointer(*resultVal))) + GetMemoryChunkContext(DatumGetPointer(*resultVal)) != CurrentMemoryContext) *resultVal = datumCopy(*resultVal, peragg->resulttypeByVal, peragg->resulttypeLen); @@ -1184,8 +1183,7 @@ finalize_partialaggregate(AggState *aggstate, /* If result is pass-by-ref, make sure it is in the right context. */ if (!peragg->resulttypeByVal && !*resultIsNull && - !MemoryContextContains(CurrentMemoryContext, - DatumGetPointer(*resultVal))) + GetMemoryChunkContext(DatumGetPointer(*resultVal)) != CurrentMemoryContext) *resultVal = datumCopy(*resultVal, peragg->resulttypeByVal, peragg->resulttypeLen); diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c index ba119046f4..2820044cd0 100644 --- a/src/backend/executor/nodeWindowAgg.c +++ b/src/backend/executor/nodeWindowAgg.c @@ -639,8 +639,7 @@ finalize_windowaggregate(WindowAggState *winstate, * If result is pass-by-ref, make sure it is in the right context. */ if (!peraggstate->resulttypeByVal && !*isnull && - !MemoryContextContains(CurrentMemoryContext, - DatumGetPointer(*result))) + GetMemoryChunkContext(DatumGetPointer(*result)) != CurrentMemoryContext) *result = datumCopy(*result, peraggstate->resulttypeByVal, peraggstate->resulttypeLen); diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index b435624d8f..3a6f12be32 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -1333,6 +1333,7 @@ AllocSetGetChunkContext(void *pointer) return &set->header; } +#ifdef MEMORY_CONTEXT_CHECKING /* * AllocSetContains * Attempt to determine if 'pointer' is memory which was allocated by @@ -1374,6 +1375,7 @@ AllocSetContains(MemoryContext context, void *pointer) } return false; } +#endif /* MEMORY_CONTEXT_CHECKING */ /* * AllocSetGetChunkSpace diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index f6a3a01912..9c0d04de08 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -848,6 +848,8 @@ GenerationGetChunkContext(void *pointer) return &block->context->header; } + +#ifdef MEMORY_CONTEXT_CHECKING /* * GenerationContains * Attempt to determine if 'pointer' is memory which was allocated by @@ -892,6 +894,7 @@ GenerationContains(MemoryContext context, void *pointer) } return false; } +#endif /* MEMORY_CONTEXT_CHECKING */ /* * GenerationGetChunkSpace diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index 3615a83d53..1097c1129c 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -44,12 +44,12 @@ static const MemoryContextMethods mcxt_methods[] = { [MCTX_ASET_ID].reset = AllocSetReset, [MCTX_ASET_ID].delete_context = AllocSetDelete, [MCTX_ASET_ID].get_chunk_context = AllocSetGetChunkContext, - [MCTX_ASET_ID].contains = AllocSetContains, [MCTX_ASET_ID].get_chunk_space = AllocSetGetChunkSpace, [MCTX_ASET_ID].is_empty = AllocSetIsEmpty, [MCTX_ASET_ID].stats = AllocSetStats, #ifdef MEMORY_CONTEXT_CHECKING [MCTX_ASET_ID].check = AllocSetCheck, + [MCTX_ASET_ID].contains = AllocSetContains, #endif /* generation.c */ @@ -59,12 +59,12 @@ static const MemoryContextMethods mcxt_methods[] = { [MCTX_GENERATION_ID].reset = GenerationReset, [MCTX_GENERATION_ID].delete_context = GenerationDelete, [MCTX_GENERATION_ID].get_chunk_context = GenerationGetChunkContext, - [MCTX_GENERATION_ID].contains = GenerationContains, [MCTX_GENERATION_ID].get_chunk_space = GenerationGetChunkSpace, [MCTX_GENERATION_ID].is_empty = GenerationIsEmpty, [MCTX_GENERATION_ID].stats = GenerationStats, #ifdef MEMORY_CONTEXT_CHECKING [MCTX_GENERATION_ID].check = GenerationCheck, + [MCTX_GENERATION_ID].contains = GenerationContains, #endif /* slab.c */ @@ -74,12 +74,12 @@ static const MemoryContextMethods mcxt_methods[] = { [MCTX_SLAB_ID].reset = SlabReset, [MCTX_SLAB_ID].delete_context = SlabDelete, [MCTX_SLAB_ID].get_chunk_context = SlabGetChunkContext, - [MCTX_SLAB_ID].contains = SlabContains, [MCTX_SLAB_ID].get_chunk_space = SlabGetChunkSpace, [MCTX_SLAB_ID].is_empty = SlabIsEmpty, [MCTX_SLAB_ID].stats = SlabStats #ifdef MEMORY_CONTEXT_CHECKING - ,[MCTX_SLAB_ID].check = SlabCheck + ,[MCTX_SLAB_ID].check = SlabCheck, + [MCTX_SLAB_ID].contains = SlabContains #endif }; @@ -816,6 +816,7 @@ MemoryContextCheck(MemoryContext context) } #endif +#ifdef MEMORY_CONTEXT_CHECKING /* * MemoryContextContains * Detect whether an allocated chunk of memory belongs to a given @@ -843,6 +844,7 @@ MemoryContextContains(MemoryContext context, void *pointer) return context->methods->contains(context, pointer); } +#endif /* MEMORY_CONTEXT_CHECKING */ /* * MemoryContextCreate diff --git a/src/backend/utils/mmgr/slab.c b/src/backend/utils/mmgr/slab.c index b5c801eb01..e46f3611ac 100644 --- a/src/backend/utils/mmgr/slab.c +++ b/src/backend/utils/mmgr/slab.c @@ -567,6 +567,7 @@ SlabGetChunkContext(void *pointer) return &slab->header; } +#ifdef MEMORY_CONTEXT_CHECKING /* * SlabContains * Attempt to determine if 'pointer' is memory which was allocated by @@ -610,6 +611,7 @@ SlabContains(MemoryContext context, void *pointer) } return false; } +#endif /* MEMORY_CONTEXT_CHECKING */ /* * SlabGetChunkSpace diff --git a/src/include/nodes/memnodes.h b/src/include/nodes/memnodes.h index 6a8d4f4e4e..6929cc8739 100644 --- a/src/include/nodes/memnodes.h +++ b/src/include/nodes/memnodes.h @@ -64,7 +64,6 @@ typedef struct MemoryContextMethods void (*reset) (MemoryContext context); void (*delete_context) (MemoryContext context); MemoryContext (*get_chunk_context) (void *pointer); - bool (*contains) (MemoryContext context, void *pointer); Size (*get_chunk_space) (void *pointer); bool (*is_empty) (MemoryContext context); void (*stats) (MemoryContext context, @@ -73,6 +72,7 @@ typedef struct MemoryContextMethods bool print_to_stderr); #ifdef MEMORY_CONTEXT_CHECKING void (*check) (MemoryContext context); + bool (*contains) (MemoryContext context, void *pointer); #endif } MemoryContextMethods; diff --git a/src/include/utils/memutils.h b/src/include/utils/memutils.h index 52bc41ec53..d7144d7307 100644 --- a/src/include/utils/memutils.h +++ b/src/include/utils/memutils.h @@ -95,8 +95,8 @@ extern void MemoryContextAllowInCriticalSection(MemoryContext context, #ifdef MEMORY_CONTEXT_CHECKING extern void MemoryContextCheck(MemoryContext context); -#endif extern bool MemoryContextContains(MemoryContext context, void *pointer); +#endif /* Handy macro for copying and assigning context ID ... but note double eval */ #define MemoryContextCopyAndSetIdentifier(cxt, id) \ diff --git a/src/include/utils/memutils_internal.h b/src/include/utils/memutils_internal.h index ebc1d60393..b767982896 100644 --- a/src/include/utils/memutils_internal.h +++ b/src/include/utils/memutils_internal.h @@ -25,7 +25,6 @@ extern void *AllocSetRealloc(void *pointer, Size size); extern void AllocSetReset(MemoryContext context); extern void AllocSetDelete(MemoryContext context); extern MemoryContext AllocSetGetChunkContext(void *pointer); -extern bool AllocSetContains(MemoryContext context, void *pointer); extern Size AllocSetGetChunkSpace(void *pointer); extern bool AllocSetIsEmpty(MemoryContext context); extern void AllocSetStats(MemoryContext context, @@ -34,6 +33,7 @@ extern void AllocSetStats(MemoryContext context, bool print_to_stderr); #ifdef MEMORY_CONTEXT_CHECKING extern void AllocSetCheck(MemoryContext context); +extern bool AllocSetContains(MemoryContext context, void *pointer); #endif /* These functions implement the MemoryContext API for Generation context. */ @@ -43,7 +43,6 @@ extern void *GenerationRealloc(void *pointer, Size size); extern void GenerationReset(MemoryContext context); extern void GenerationDelete(MemoryContext context); extern MemoryContext GenerationGetChunkContext(void *pointer); -extern bool GenerationContains(MemoryContext context, void *pointer); extern Size GenerationGetChunkSpace(void *pointer); extern bool GenerationIsEmpty(MemoryContext context); extern void GenerationStats(MemoryContext context, @@ -52,6 +51,7 @@ extern void GenerationStats(MemoryContext context, bool print_to_stderr); #ifdef MEMORY_CONTEXT_CHECKING extern void GenerationCheck(MemoryContext context); +extern bool GenerationContains(MemoryContext context, void *pointer); #endif @@ -62,7 +62,6 @@ extern void *SlabRealloc(void *pointer, Size size); extern void SlabReset(MemoryContext context); extern void SlabDelete(MemoryContext context); extern MemoryContext SlabGetChunkContext(void *pointer); -extern bool SlabContains(MemoryContext context, void *pointer); extern Size SlabGetChunkSpace(void *pointer); extern bool SlabIsEmpty(MemoryContext context); extern void SlabStats(MemoryContext context, @@ -71,6 +70,7 @@ extern void SlabStats(MemoryContext context, bool print_to_stderr); #ifdef MEMORY_CONTEXT_CHECKING extern void SlabCheck(MemoryContext context); +extern bool SlabContains(MemoryContext context, void *pointer); #endif /* -- 2.34.1
asserts.patch (text/plain, 3.0K) download diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c index 323ae94938..a6428a77c4 100644 --- a/src/backend/executor/nodeAgg.c +++ b/src/backend/executor/nodeAgg.c @@ -1108,6 +1108,9 @@ finalize_aggregate(AggState *aggstate, { *resultVal = FunctionCallInvoke(fcinfo); *resultIsNull = fcinfo->isnull; + Assert(peragg->resulttypeByVal || + *resultIsNull || + GetMemoryChunkContext(DatumGetPointer(*resultVal)) == CurrentMemoryContext); } aggstate->curperagg = NULL; } @@ -1116,6 +1119,9 @@ finalize_aggregate(AggState *aggstate, /* Don't need MakeExpandedObjectReadOnly; datumCopy will copy it */ *resultVal = pergroupstate->transValue; *resultIsNull = pergroupstate->transValueIsNull; + Assert(peragg->resulttypeByVal || + *resultIsNull || + GetMemoryChunkContext(DatumGetPointer(*resultVal)) != CurrentMemoryContext); } /* @@ -1172,6 +1178,10 @@ finalize_partialaggregate(AggState *aggstate, *resultVal = FunctionCallInvoke(fcinfo); *resultIsNull = fcinfo->isnull; + + Assert(peragg->resulttypeByVal || + *resultIsNull || + GetMemoryChunkContext(DatumGetPointer(*resultVal)) == CurrentMemoryContext); } } else @@ -1179,6 +1189,10 @@ finalize_partialaggregate(AggState *aggstate, /* Don't need MakeExpandedObjectReadOnly; datumCopy will copy it */ *resultVal = pergroupstate->transValue; *resultIsNull = pergroupstate->transValueIsNull; + Assert(peragg->resulttypeByVal || + *resultIsNull || + GetMemoryChunkContext(DatumGetPointer(*resultVal)) != CurrentMemoryContext); + } /* If result is pass-by-ref, make sure it is in the right context. */ diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c index 2820044cd0..3e4462b4c4 100644 --- a/src/backend/executor/nodeWindowAgg.c +++ b/src/backend/executor/nodeWindowAgg.c @@ -626,6 +626,10 @@ finalize_windowaggregate(WindowAggState *winstate, *result = FunctionCallInvoke(fcinfo); winstate->curaggcontext = NULL; *isnull = fcinfo->isnull; + + Assert(peraggstate->resulttypeByVal || + *isnull || + GetMemoryChunkContext(DatumGetPointer(*result)) == CurrentMemoryContext); } } else @@ -633,6 +637,9 @@ finalize_windowaggregate(WindowAggState *winstate, /* Don't need MakeExpandedObjectReadOnly; datumCopy will copy it */ *result = peraggstate->transValue; *isnull = peraggstate->transValueIsNull; + Assert(peraggstate->resulttypeByVal || + *isnull || + GetMemoryChunkContext(DatumGetPointer(*result)) != CurrentMemoryContext); } /* @@ -1060,6 +1067,10 @@ eval_windowfunction(WindowAggState *winstate, WindowStatePerFunc perfuncstate, *result = FunctionCallInvoke(fcinfo); *isnull = fcinfo->isnull; + Assert(perfuncstate->resulttypeByVal || + *isnull || + GetMemoryChunkContext(DatumGetPointer(*result)) == CurrentMemoryContext); + /* * Make sure pass-by-ref data is allocated in the appropriate context. (We * need this in case the function returns a pointer into some short-lived
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-20 01:11  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-09-20 01:11 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 13 Sept 2022 at 20:27, David Rowley <dgrowleyml@gmail.com> wrote:
> I see that one of the drawbacks from not using MemoryContextContains()
> is that window functions such as lead(), lag(), first_value(),
> last_value() and nth_value() may now do the datumCopy() when it's not
> needed. For example, with a window function call such as
> lead(byref_col ), the expression evaluation code in
> WinGetFuncArgInPartition() will just return the address in the
> tuplestore tuple for "byref_col".  The datumCopy() is needed for that.
> However, if the function call was lead(byref_col || 'something') then
> we'd have ended up with a new allocation in CurrentMemoryContext to
> concatenate the two values.  We'll now do a datumCopy() where we
> previously wouldn't have. I don't really see any way around that
> without doing some highly invasive surgery to the expression
> evaluation code.

It feels like a terrible idea, but  I wondered if we could look at the
WindowFunc->args and make a decision if we should do the datumCopy()
based on the type of the argument. Vars would need to be copied as
they will point into the tuple's memory, but an OpExpr likely would
not need to be copied.

Aside from that, I don't have any ideas on how to get rid of the
possible additional datumCopy() from non-Var arguments to these window
functions.  Should we just suffer it? It's quite likely that most
arguments to these functions are plain Vars anyway.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-20 01:23  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 2 replies; 152+ messages in thread

From: Tom Lane @ 2022-09-20 01:23 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> Aside from that, I don't have any ideas on how to get rid of the
> possible additional datumCopy() from non-Var arguments to these window
> functions.  Should we just suffer it? It's quite likely that most
> arguments to these functions are plain Vars anyway.

No, we shouldn't.  I'm pretty sure that we have various window
functions that are deliberately designed to take advantage of the
no-copy behavior, and that they have taken a significant speed
hit from your having disabled that optimization.  I don't say
that this is enough to justify reverting the chunk header changes
altogether ... but I'm completely not satisfied with the current
situation in HEAD.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-20 04:49  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-09-20 04:49 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 20 Sept 2022 at 13:23, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> David Rowley <dgrowleyml@gmail.com> writes:
> > Aside from that, I don't have any ideas on how to get rid of the
> > possible additional datumCopy() from non-Var arguments to these window
> > functions.  Should we just suffer it? It's quite likely that most
> > arguments to these functions are plain Vars anyway.
>
> No, we shouldn't.  I'm pretty sure that we have various window
> functions that are deliberately designed to take advantage of the
> no-copy behavior, and that they have taken a significant speed
> hit from your having disabled that optimization.  I don't say
> that this is enough to justify reverting the chunk header changes
> altogether ... but I'm completely not satisfied with the current
> situation in HEAD.

Maybe you've forgotten that MemoryContextContains() is broken in the
back branches or just don't think it is broken?

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-20 05:23  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-09-20 05:23 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> On Tue, 20 Sept 2022 at 13:23, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> ... but I'm completely not satisfied with the current
>> situation in HEAD.

> Maybe you've forgotten that MemoryContextContains() is broken in the
> back branches or just don't think it is broken?

"Broken" is a strong claim.  There's reason to think it could fail
in the back branches, but little evidence that it actually has failed
in the field.  So yeah, we have work to do --- which is the exact
opposite of your apparent stand that we can walk away from the
problem.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-20 06:10  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 0 replies; 152+ messages in thread

From: David Rowley @ 2022-09-20 06:10 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 20 Sept 2022 at 17:23, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> "Broken" is a strong claim.  There's reason to think it could fail
> in the back branches, but little evidence that it actually has failed
> in the field.

I've posted some code to the security list that shows that I can get
MemoryContextContains() to return true when it should return false.
This results in the datumCopy() in eval_windowfunction() being skipped
and the result of the window function being left in the incorrect
memory context.  I was unable to get this to produce a crash, but if
there's some way to have the result point into a shared buffer page
and that page is evicted and replaced with something else before the
value is used then we'd have issues.

>  So yeah, we have work to do --- which is the exact
> opposite of your apparent stand that we can walk away from the
> problem.

My problem is that I'm unable to think of a way to fix something I see
as an existing bug. I've given it a week and nobody else has come
forward with any proposals on how to fix this. I'm very open to
finding some way to allow us to keep this optimisation, but so far
I've been unable to. We have reverted broken optimisations before.
Also, reverting c6e0fe1f2a does not seem that appealing to me as it
just returns MemoryContextContains() back into a state where it can
return false positives again.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-26 22:28  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-09-26 22:28 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 20 Sept 2022 at 13:23, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> David Rowley <dgrowleyml@gmail.com> writes:
> > Aside from that, I don't have any ideas on how to get rid of the
> > possible additional datumCopy() from non-Var arguments to these window
> > functions.  Should we just suffer it? It's quite likely that most
> > arguments to these functions are plain Vars anyway.
>
> No, we shouldn't.  I'm pretty sure that we have various window
> functions that are deliberately designed to take advantage of the
> no-copy behavior, and that they have taken a significant speed
> hit from your having disabled that optimization.  I don't say
> that this is enough to justify reverting the chunk header changes
> altogether ... but I'm completely not satisfied with the current
> situation in HEAD.

Looking more closely at window_gettupleslot(), it always allocates the
tuple in ecxt_per_query_memory, so any column we fetch out of that
tuple will be in that memory context.  window_gettupleslot() is used
in lead(), lag(), first_value(), last_value() and nth_value() to fetch
the Nth tuple out of the partition window. The other window functions
all return BIGINT, FLOAT8 or INT which are byval on 64-bit, and on
32-bit these functions return a freshly palloc'd Datum in the
CurrentMemoryContext.

Maybe we could remove the datumCopy() from eval_windowfunction() and
also document that a window function when returning a non-byval type,
must allocate the Datum in either ps_ExprContext's
ecxt_per_tuple_memory or ecxt_per_query_memory. We could ensure any
extension which has its own window functions get the memo about the
API change by adding an Assert to ensure that the return value (for
byref types) is in the current context by calling the
loop-over-the-blocks version of MemoryContextContains().

This would mean that wfuncs like lead(column_name) would no longer do
that extra datumCopy and the likes of lead(col || 'some OpExpr') would
save a little as we'd no longer call MemoryContextContains on
non-Assert builds.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-09-29 05:30  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-09-29 05:30 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 27 Sept 2022 at 11:28, David Rowley <dgrowleyml@gmail.com> wrote:
> Maybe we could remove the datumCopy() from eval_windowfunction() and
> also document that a window function when returning a non-byval type,
> must allocate the Datum in either ps_ExprContext's
> ecxt_per_tuple_memory or ecxt_per_query_memory. We could ensure any
> extension which has its own window functions get the memo about the
> API change by adding an Assert to ensure that the return value (for
> byref types) is in the current context by calling the
> loop-over-the-blocks version of MemoryContextContains().

I did some work on this and it turned out that the value returned by
any of lead(), lag(), first_value(), last_value() and nth_value()
could also be in MessageContext or some child context to
CacheMemoryContext.  The reason for the latter two is that cases like
LAG(col, 1, 'default value') will return the Const in the 3rd arg when
the offset value is outside of the window frame. That means
MessageContext for normal queries and it means it'll be cached in a
child context of CacheMemoryContext for PREPAREd queries.

This means the Assert that I wanted to add to eval_windowfunction
became quite complex. Namely:

Assert(perfuncstate->resulttypeByVal || fcinfo->isnull ||
   MemoryContextContains(winstate->ss.ps.ps_ExprContext->ecxt_per_tuple_memory,
(void *) *result) ||
   MemoryContextContains(winstate->ss.ps.ps_ExprContext->ecxt_per_query_memory,
(void *) *result) ||
   MemoryContextContains(MessageContext, (void *) *result) ||
   MemoryContextOrChildOfContains(CacheMemoryContext, (void *) *result));

Notice the invention of MemoryContextOrChildOfContains() to
recursively search the CacheMemoryContext children. It does not seem
so great as CacheMemoryContext tends to have many children and
searching through them all could make that Assert a bit slow.

I think I am fairly happy that all the 4 message contexts I mentioned
in the Assert will be around long enough for the result value to not
be freed. It's just that the whole thing feels a bit wrong and that
the context the return value is in should be a bit more predictable.

Does anyone have any opinions on this?

David

Attachments:

other_ideas_to_fix_MemoryContextContains.patch (text/plain, 20.3K) download diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c index fe74e49814..bc7eeaf84d 100644 --- a/src/backend/executor/nodeAgg.c +++ b/src/backend/executor/nodeAgg.c @@ -1107,6 +1107,11 @@ finalize_aggregate(AggState *aggstate, { *resultVal = FunctionCallInvoke(fcinfo); *resultIsNull = fcinfo->isnull; + + /* ensure by-ref types are allocated in CurrentMemoryContext */ + Assert(peragg->resulttypeByVal || *resultIsNull || + MemoryContextContains(CurrentMemoryContext, (void *) *resultVal)); + } aggstate->curperagg = NULL; } @@ -1115,17 +1120,13 @@ finalize_aggregate(AggState *aggstate, /* Don't need MakeExpandedObjectReadOnly; datumCopy will copy it */ *resultVal = pergroupstate->transValue; *resultIsNull = pergroupstate->transValueIsNull; - } - /* - * If result is pass-by-ref, make sure it is in the right context. - */ - if (!peragg->resulttypeByVal && !*resultIsNull && - !MemoryContextContains(CurrentMemoryContext, - DatumGetPointer(*resultVal))) - *resultVal = datumCopy(*resultVal, - peragg->resulttypeByVal, - peragg->resulttypeLen); + /* if result is pass-by-ref, copy into the CurrentMemoryContext */ + if (!peragg->resulttypeByVal && !*resultIsNull) + *resultVal = datumCopy(*resultVal, + peragg->resulttypeByVal, + peragg->resulttypeLen); + } MemoryContextSwitchTo(oldContext); } @@ -1172,6 +1173,11 @@ finalize_partialaggregate(AggState *aggstate, *resultVal = FunctionCallInvoke(fcinfo); *resultIsNull = fcinfo->isnull; + + /* ensure by-ref types are allocated in CurrentMemoryContext */ + Assert(peragg->resulttypeByVal || *resultIsNull || + MemoryContextContains(CurrentMemoryContext, (void *) *resultVal)); + } } else @@ -1179,15 +1185,14 @@ finalize_partialaggregate(AggState *aggstate, /* Don't need MakeExpandedObjectReadOnly; datumCopy will copy it */ *resultVal = pergroupstate->transValue; *resultIsNull = pergroupstate->transValueIsNull; - } - /* If result is pass-by-ref, make sure it is in the right context. */ - if (!peragg->resulttypeByVal && !*resultIsNull && - !MemoryContextContains(CurrentMemoryContext, - DatumGetPointer(*resultVal))) - *resultVal = datumCopy(*resultVal, - peragg->resulttypeByVal, - peragg->resulttypeLen); + /* if result is pass-by-ref, copy into the CurrentMemoryContext */ + if (!peragg->resulttypeByVal && !*resultIsNull) + *resultVal = datumCopy(*resultVal, + peragg->resulttypeByVal, + peragg->resulttypeLen); + + } MemoryContextSwitchTo(oldContext); } diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c index 8b0858e9f5..b196328060 100644 --- a/src/backend/executor/nodeWindowAgg.c +++ b/src/backend/executor/nodeWindowAgg.c @@ -626,6 +626,10 @@ finalize_windowaggregate(WindowAggState *winstate, *result = FunctionCallInvoke(fcinfo); winstate->curaggcontext = NULL; *isnull = fcinfo->isnull; + + /* ensure by-ref types are allocated in CurrentMemoryContext */ + Assert(peraggstate->resulttypeByVal || *isnull || + MemoryContextContains(CurrentMemoryContext, (void *) *result)); } } else @@ -633,17 +637,14 @@ finalize_windowaggregate(WindowAggState *winstate, /* Don't need MakeExpandedObjectReadOnly; datumCopy will copy it */ *result = peraggstate->transValue; *isnull = peraggstate->transValueIsNull; + + /* if result is pass-by-ref, copy into the CurrentMemoryContext */ + if (!peraggstate->resulttypeByVal && !*isnull) + *result = datumCopy(*result, + peraggstate->resulttypeByVal, + peraggstate->resulttypeLen); } - /* - * If result is pass-by-ref, make sure it is in the right context. - */ - if (!peraggstate->resulttypeByVal && !*isnull && - !MemoryContextContains(CurrentMemoryContext, - DatumGetPointer(*result))) - *result = datumCopy(*result, - peraggstate->resulttypeByVal, - peraggstate->resulttypeLen); MemoryContextSwitchTo(oldContext); } @@ -1034,9 +1035,13 @@ eval_windowfunction(WindowAggState *winstate, WindowStatePerFunc perfuncstate, { LOCAL_FCINFO(fcinfo, FUNC_MAX_ARGS); MemoryContext oldContext; + WindowResultInfo resultinfo; oldContext = MemoryContextSwitchTo(winstate->ss.ps.ps_ExprContext->ecxt_per_tuple_memory); + resultinfo.resulttypeLen = perfuncstate->resulttypeLen; + resultinfo.resulttypeByVal = perfuncstate->resulttypeByVal; + /* * We don't pass any normal arguments to a window function, but we do pass * it the number of arguments, in order to permit window function @@ -1046,7 +1051,8 @@ eval_windowfunction(WindowAggState *winstate, WindowStatePerFunc perfuncstate, InitFunctionCallInfoData(*fcinfo, &(perfuncstate->flinfo), perfuncstate->numArguments, perfuncstate->winCollation, - (void *) perfuncstate->winobj, NULL); + (void *) perfuncstate->winobj, + (void *) &resultinfo); /* Just in case, make all the regular argument slots be null */ for (int argno = 0; argno < perfuncstate->numArguments; argno++) fcinfo->args[argno].isnull = true; @@ -1057,16 +1063,15 @@ eval_windowfunction(WindowAggState *winstate, WindowStatePerFunc perfuncstate, *isnull = fcinfo->isnull; /* - * Make sure pass-by-ref data is allocated in the appropriate context. (We - * need this in case the function returns a pointer into some short-lived - * tuple, as is entirely possible.) + * Ensure byref Datums are allocated in the tuple or query context. The + * result may also be a Const which is stored in the MessageContext or + * cached by some cached plan. */ - if (!perfuncstate->resulttypeByVal && !fcinfo->isnull && - !MemoryContextContains(CurrentMemoryContext, - DatumGetPointer(*result))) - *result = datumCopy(*result, - perfuncstate->resulttypeByVal, - perfuncstate->resulttypeLen); + Assert(perfuncstate->resulttypeByVal || fcinfo->isnull || + MemoryContextContains(winstate->ss.ps.ps_ExprContext->ecxt_per_tuple_memory, (void *) *result) || + MemoryContextContains(winstate->ss.ps.ps_ExprContext->ecxt_per_query_memory, (void *) *result) || + MemoryContextContains(MessageContext, (void *) *result) || + MemoryContextOrChildOfContains(CacheMemoryContext, (void *) *result)); MemoryContextSwitchTo(oldContext); } diff --git a/src/backend/utils/adt/numeric.c b/src/backend/utils/adt/numeric.c index 85ee9ec426..f9eaa413e9 100644 --- a/src/backend/utils/adt/numeric.c +++ b/src/backend/utils/adt/numeric.c @@ -6643,7 +6643,7 @@ int2int4_sum(PG_FUNCTION_ARGS) if (transdata->count == 0) PG_RETURN_NULL(); - PG_RETURN_DATUM(Int64GetDatumFast(transdata->sum)); + PG_RETURN_DATUM(Int64GetDatum(transdata->sum)); } diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index ec423375ae..a67d72016e 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -1333,6 +1333,28 @@ AllocSetGetChunkContext(void *pointer) return &set->header; } +#ifdef MEMORY_CONTEXT_CHECKING +/* + * AllocSetContains + * Attempt to determine if 'pointer' is memory which was allocated by + * 'context'. Return true if it is, otherwise false. + */ +bool +AllocSetContains(MemoryContext context, void *pointer) +{ + AllocSet set = (AllocSet) context; + + for (AllocBlock blk = set->blocks; blk != NULL; blk = blk->next) + { + /* see if pointer is in range of this block */ + if ((char *) pointer >= (char *) blk + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ && + (char *) pointer < blk->endptr) + return true; + } + return false; +} +#endif /* MEMORY_CONTEXT_CHECKING */ + /* * AllocSetGetChunkSpace * Given a currently-allocated chunk, determine the total space diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index c743b24fa7..e44f765f35 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -848,6 +848,32 @@ GenerationGetChunkContext(void *pointer) return &block->context->header; } + +#ifdef MEMORY_CONTEXT_CHECKING +/* + * GenerationContains + * Attempt to determine if 'pointer' is memory which was allocated by + * 'context'. Return true if it is, otherwise false. + */ +bool +GenerationContains(MemoryContext context, void *pointer) +{ + GenerationContext *set = (GenerationContext *) context; + dlist_iter iter; + + dlist_foreach(iter, &set->blocks) + { + GenerationBlock *blk = dlist_container(GenerationBlock, node, iter.cur); + + /* see if pointer is in range of this block */ + if ((char *) pointer >= (char *) blk + Generation_BLOCKHDRSZ + Generation_CHUNKHDRSZ && + (char *) pointer < blk->endptr) + return true; + } + return false; +} +#endif /* MEMORY_CONTEXT_CHECKING */ + /* * GenerationGetChunkSpace * Given a currently-allocated chunk, determine the total space diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index 115a64cfe4..637cb1a569 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -49,6 +49,7 @@ static const MemoryContextMethods mcxt_methods[] = { [MCTX_ASET_ID].stats = AllocSetStats, #ifdef MEMORY_CONTEXT_CHECKING [MCTX_ASET_ID].check = AllocSetCheck, + [MCTX_ASET_ID].contains = AllocSetContains, #endif /* generation.c */ @@ -63,6 +64,7 @@ static const MemoryContextMethods mcxt_methods[] = { [MCTX_GENERATION_ID].stats = GenerationStats, #ifdef MEMORY_CONTEXT_CHECKING [MCTX_GENERATION_ID].check = GenerationCheck, + [MCTX_GENERATION_ID].contains = GenerationContains, #endif /* slab.c */ @@ -76,7 +78,8 @@ static const MemoryContextMethods mcxt_methods[] = { [MCTX_SLAB_ID].is_empty = SlabIsEmpty, [MCTX_SLAB_ID].stats = SlabStats #ifdef MEMORY_CONTEXT_CHECKING - ,[MCTX_SLAB_ID].check = SlabCheck + ,[MCTX_SLAB_ID].check = SlabCheck, + [MCTX_SLAB_ID].contains = SlabContains #endif }; @@ -813,48 +816,51 @@ MemoryContextCheck(MemoryContext context) } #endif +#ifdef MEMORY_CONTEXT_CHECKING /* * MemoryContextContains * Detect whether an allocated chunk of memory belongs to a given * context or not. * - * Caution: 'pointer' must point to a pointer which was allocated by a - * MemoryContext. It's not safe or valid to use this function on arbitrary - * pointers as obtaining the MemoryContext which 'pointer' belongs to requires - * possibly several pointer dereferences. + * Caution: this test is reliable as long as 'pointer' does point to + * a chunk of memory allocated from *some* context. If 'pointer' points + * at memory obtained in some other way, there is a chance of a segmentation + * violation due to accessing the chunk header, which look for in the 8 bytes + * prior to the pointer. */ bool MemoryContextContains(MemoryContext context, void *pointer) { - /* - * Temporarily make this always return false as we don't yet have a fully - * baked idea on how to make it work correctly with the new MemoryChunk - * code. - */ - return false; + if (pointer == NULL) + return false; -#ifdef NOT_USED - MemoryContext ptr_context; + return context->methods->contains(context, pointer); +} - /* - * NB: We must perform run-time checks here which GetMemoryChunkContext() - * does as assertions before calling GetMemoryChunkContext(). - * - * Try to detect bogus pointers handed to us, poorly though we can. - * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an - * allocated chunk. - */ - if (pointer == NULL || pointer != (void *) MAXALIGN(pointer)) - return false; +/* + * MemoryContextOrChildOfContains + * Recursive version of MemoryContextContains which checks if any of + * context's child contexts contains the pointer. + */ +bool +MemoryContextOrChildOfContains(MemoryContext context, void *pointer) +{ + if (MemoryContextContains(context, pointer)) + return true; + else + { + MemoryContext child; - /* - * OK, it's probably safe to look at the context. - */ - ptr_context = GetMemoryChunkContext(pointer); + for (child = context->firstchild; child != NULL; child = child->nextchild) + { + if (MemoryContextOrChildOfContains(child, pointer)) + return true; + } + } - return ptr_context == context; -#endif + return false; } +#endif /* MEMORY_CONTEXT_CHECKING */ /* * MemoryContextCreate @@ -969,6 +975,8 @@ MemoryContextAlloc(MemoryContext context, Size size) VALGRIND_MEMPOOL_ALLOC(context, ret, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1007,6 +1015,8 @@ MemoryContextAllocZero(MemoryContext context, Size size) MemSetAligned(ret, 0, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1045,6 +1055,8 @@ MemoryContextAllocZeroAligned(MemoryContext context, Size size) MemSetLoop(ret, 0, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1086,6 +1098,8 @@ MemoryContextAllocExtended(MemoryContext context, Size size, int flags) if ((flags & MCXT_ALLOC_ZERO) != 0) MemSetAligned(ret, 0, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1169,6 +1183,8 @@ palloc(Size size) VALGRIND_MEMPOOL_ALLOC(context, ret, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1202,6 +1218,8 @@ palloc0(Size size) MemSetAligned(ret, 0, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1241,6 +1259,8 @@ palloc_extended(Size size, int flags) if ((flags & MCXT_ALLOC_ZERO) != 0) MemSetAligned(ret, 0, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1294,6 +1314,8 @@ repalloc(void *pointer, Size size) VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1329,6 +1351,8 @@ MemoryContextAllocHuge(MemoryContext context, Size size) VALGRIND_MEMPOOL_ALLOC(context, ret, size); + Assert(MemoryContextContains(context, ret)); + return ret; } @@ -1368,6 +1392,8 @@ repalloc_huge(void *pointer, Size size) VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size); + Assert(MemoryContextContains(context, ret)); + return ret; } diff --git a/src/backend/utils/mmgr/slab.c b/src/backend/utils/mmgr/slab.c index 9149aaafcb..f5ad699760 100644 --- a/src/backend/utils/mmgr/slab.c +++ b/src/backend/utils/mmgr/slab.c @@ -567,6 +567,35 @@ SlabGetChunkContext(void *pointer) return &slab->header; } +#ifdef MEMORY_CONTEXT_CHECKING +/* + * SlabContains + * Attempt to determine if 'pointer' is memory which was allocated by + * 'context'. Return true if it is, otherwise false. + */ +bool +SlabContains(MemoryContext context, void *pointer) +{ + SlabContext *set = (SlabContext *) context; + + for (int i = 0; i <= set->chunksPerBlock; i++) + { + dlist_iter iter; + + dlist_foreach(iter, &set->freelist[i]) + { + SlabBlock *blk = dlist_container(SlabBlock, node, iter.cur); + + /* see if pointer is in range of this block */ + if ((char *) pointer >= (char *) blk + Slab_BLOCKHDRSZ + Slab_CHUNKHDRSZ && + (char *) pointer < (char *) blk + set->blockSize) + return true; + } + } + return false; +} +#endif /* MEMORY_CONTEXT_CHECKING */ + /* * SlabGetChunkSpace * Given a currently-allocated chunk, determine the total space diff --git a/src/include/nodes/memnodes.h b/src/include/nodes/memnodes.h index 63d07358cd..c1d6fd5391 100644 --- a/src/include/nodes/memnodes.h +++ b/src/include/nodes/memnodes.h @@ -72,6 +72,7 @@ typedef struct MemoryContextMethods bool print_to_stderr); #ifdef MEMORY_CONTEXT_CHECKING void (*check) (MemoryContext context); + bool (*contains) (MemoryContext context, void *pointer); #endif } MemoryContextMethods; diff --git a/src/include/utils/memutils.h b/src/include/utils/memutils.h index 52bc41ec53..3bfadbd465 100644 --- a/src/include/utils/memutils.h +++ b/src/include/utils/memutils.h @@ -95,8 +95,10 @@ extern void MemoryContextAllowInCriticalSection(MemoryContext context, #ifdef MEMORY_CONTEXT_CHECKING extern void MemoryContextCheck(MemoryContext context); -#endif extern bool MemoryContextContains(MemoryContext context, void *pointer); +extern bool MemoryContextOrChildOfContains(MemoryContext context, + void *pointer); +#endif /* Handy macro for copying and assigning context ID ... but note double eval */ #define MemoryContextCopyAndSetIdentifier(cxt, id) \ diff --git a/src/include/utils/memutils_internal.h b/src/include/utils/memutils_internal.h index 377cee7a84..b767982896 100644 --- a/src/include/utils/memutils_internal.h +++ b/src/include/utils/memutils_internal.h @@ -33,6 +33,7 @@ extern void AllocSetStats(MemoryContext context, bool print_to_stderr); #ifdef MEMORY_CONTEXT_CHECKING extern void AllocSetCheck(MemoryContext context); +extern bool AllocSetContains(MemoryContext context, void *pointer); #endif /* These functions implement the MemoryContext API for Generation context. */ @@ -50,6 +51,7 @@ extern void GenerationStats(MemoryContext context, bool print_to_stderr); #ifdef MEMORY_CONTEXT_CHECKING extern void GenerationCheck(MemoryContext context); +extern bool GenerationContains(MemoryContext context, void *pointer); #endif @@ -68,6 +70,7 @@ extern void SlabStats(MemoryContext context, bool print_to_stderr); #ifdef MEMORY_CONTEXT_CHECKING extern void SlabCheck(MemoryContext context); +extern bool SlabContains(MemoryContext context, void *pointer); #endif /* diff --git a/src/include/utils/memutils_memorychunk.h b/src/include/utils/memutils_memorychunk.h index 2eefc138e3..a6a0137e5d 100644 --- a/src/include/utils/memutils_memorychunk.h +++ b/src/include/utils/memutils_memorychunk.h @@ -107,9 +107,18 @@ MEMORYCHUNK_VALUE_BASEBIT << \ MEMORYCHUNK_VALUE_BASEBIT) +#ifdef MEMORY_CONTEXT_CHECKING +#if SIZEOF_SIZE_T >= 8 +#define MEMORYCHUNK_MAGIC2 UINT64CONST(0xB1A8DB858EB6EFBA) +#else +#define MEMORYCHUNK_MAGIC2 0x8EB6EFBA +#endif +#endif + typedef struct MemoryChunk { #ifdef MEMORY_CONTEXT_CHECKING + Size chunk_magic; /* magic number */ Size requested_size; #endif @@ -161,6 +170,9 @@ MemoryChunkSetHdrMask(MemoryChunk *chunk, void *block, Assert(value <= MEMORYCHUNK_MAX_VALUE); Assert((int) methodid <= MEMORY_CONTEXT_METHODID_MASK); +#ifdef MEMORY_CONTEXT_CHECKING + chunk->chunk_magic = MEMORYCHUNK_MAGIC2; +#endif chunk->hdrmask = (((uint64) blockoffset) << MEMORYCHUNK_BLOCKOFFSET_BASEBIT) | (((uint64) value) << MEMORYCHUNK_VALUE_BASEBIT) | methodid; @@ -177,6 +189,9 @@ MemoryChunkSetHdrMaskExternal(MemoryChunk *chunk, { Assert((int) methodid <= MEMORY_CONTEXT_METHODID_MASK); +#ifdef MEMORY_CONTEXT_CHECKING + chunk->chunk_magic = MEMORYCHUNK_MAGIC2; +#endif chunk->hdrmask = MEMORYCHUNK_MAGIC | (((uint64) 1) << MEMORYCHUNK_EXTERNAL_BASEBIT) | methodid; } @@ -194,6 +209,7 @@ MemoryChunkIsExternal(MemoryChunk *chunk) */ Assert(!HdrMaskIsExternal(chunk->hdrmask) || HdrMaskCheckMagic(chunk->hdrmask)); + Assert(chunk->chunk_magic == MEMORYCHUNK_MAGIC2); return HdrMaskIsExternal(chunk->hdrmask); } @@ -207,6 +223,7 @@ static inline Size MemoryChunkGetValue(MemoryChunk *chunk) { Assert(!HdrMaskIsExternal(chunk->hdrmask)); + Assert(chunk->chunk_magic == MEMORYCHUNK_MAGIC2); return HdrMaskGetValue(chunk->hdrmask); } @@ -220,6 +237,7 @@ static inline void * MemoryChunkGetBlock(MemoryChunk *chunk) { Assert(!HdrMaskIsExternal(chunk->hdrmask)); + Assert(chunk->chunk_magic == MEMORYCHUNK_MAGIC2); return (void *) ((char *) chunk - HdrMaskBlockOffset(chunk->hdrmask)); } @@ -229,6 +247,7 @@ MemoryChunkGetBlock(MemoryChunk *chunk) #undef MEMORYCHUNK_VALUE_BASEBIT #undef MEMORYCHUNK_BLOCKOFFSET_BASEBIT #undef MEMORYCHUNK_MAGIC +#undef MEMORYCHUNK_MAGIC2 #undef HdrMaskIsExternal #undef HdrMaskGetValue #undef HdrMaskBlockOffset diff --git a/src/include/windowapi.h b/src/include/windowapi.h index 5a620a2e42..c3d65b161c 100644 --- a/src/include/windowapi.h +++ b/src/include/windowapi.h @@ -36,7 +36,19 @@ /* this struct is private in nodeWindowAgg.c */ typedef struct WindowObjectData *WindowObject; +/* + * Evaluation of window functions are passed this object and it's available + * via fcinfo->resultinfo and can be accessed in the window function via the + * PG_WINDOW_RESULTINFO macro. + */ +typedef struct WindowResultInfo +{ + int16 resulttypeLen; /* type length of wfunc's result type */ + bool resulttypeByVal; /* true if wfunc's result is byval */ +} WindowResultInfo; + #define PG_WINDOW_OBJECT() ((WindowObject) fcinfo->context) +#define PG_WINDOW_RESULTINFO() ((WindowResultInfo *) fcinfo->resultinfo) #define WindowObjectIsValid(winobj) \ ((winobj) != NULL && IsA(winobj, WindowObjectData))
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-02 23:43  David Rowley <dgrowleyml@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-10-02 23:43 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Thu, 29 Sept 2022 at 18:30, David Rowley <dgrowleyml@gmail.com> wrote:
> Does anyone have any opinions on this?

I by no means think I've nailed the fix in
other_ideas_to_fix_MemoryContextContains.patch, so it would be good to
see if anyone else has any new ideas on how to solve this issue.

Andres did mention to me off-list about perhaps adding a boolean field
to FunctionCallInfoBaseData to indicate if the return value can be
assumed to be in CurrentMemoryContext.  I feel like that might be
quite a bit of work to go and change all functions to ensure that
that's properly populated. For example, look at split_part() in
varlena.c, it's going to be a little tedious to ensure we set that
field correctly there as that function sometimes returns it's input,
sometimes returns a string constant and sometimes allocates new
memory.  I feel fixing it this way will be error-prone and cause lots
of future bugs.

I'm also aware that the change made in b76fb6c2a becomes less
temporary with each day that passes, so I really would like to find a
solution to the MemoryContextContains issue. I'll reiterate that I
don't think reverting c6e0fe1f2 fixes MemoryContextContains. That
would just put back the behaviour of it returning true based on the
owning MemoryContext and/or the direction that the wind is coming from
on the particular day the function is called.

Although I do think other_ideas_to_fix_MemoryContextContains.patch
does fix the problem. I also fear a few people would be reaching for
their pitchforks if I was to go and commit it. However, as of now, I'm
starting to look more favourably at it as more time passes.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-03 19:37  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-10-03 19:37 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> Andres did mention to me off-list about perhaps adding a boolean field
> to FunctionCallInfoBaseData to indicate if the return value can be
> assumed to be in CurrentMemoryContext.  I feel like that might be
> quite a bit of work to go and change all functions to ensure that
> that's properly populated.

That seems like the right basic answer, but wrong in detail.  We have only
a tiny number of places that care about this --- aggregates and window
functions basically --- and those already have a bunch of special calling
conventions.  So changing the generic fmgr APIs has side-effects far
beyond what's justified.

I think what we should look at is extending the aggregate/window
function APIs so that such functions can report where they put their
output, and then we can nuke MemoryContextContains(), with the
code code set up to assume that it has to copy if the called function
didn't report anything.  The existing FunctionCallInfo.resultinfo
mechanism (cf. ReturnSetInfo for SRFs) is probably the right thing
to pass the flag through.

I can take a look at this once the release dust settles a little.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-04 00:35  Ranier Vilela <ranier.vf@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: Ranier Vilela @ 2022-10-04 00:35 UTC (permalink / raw)
  To: pgsql-hackers; +Cc: David Rowley <dgrowleyml@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>

 On Thu, 29 Sept 2022 at 18:30, David Rowley <dgrowleyml(at)gmail(dot)com>
wrote:
> Does anyone have any opinions on this?
Hi,

Revisiting my work on reducing memory consumption, I found this patch left
out.
I'm not sure I can help.
But basically I was able to write and read the block size, in the chunk.
Could it be the case of writing and reading the context pointer in the same
way?
Sure this leads to some performance loss, but would it make it possible to
get the context pointer from the chunk?
In other words, would it be possible to save the context pointer and
compare it later in MemoryContextContains?

regards,
Ranier Vilela

Attachments:

001-reduces-memory-consumption.patch (application/octet-stream, 11.2K) download diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index ec3e264a73..fbe33ad87e 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -150,11 +150,13 @@ typedef AllocSetContext *AllocSet; */ typedef struct AllocBlockData { - AllocSet aset; /* aset that owns this block */ AllocBlock prev; /* prev block in aset's blocks list, if any */ AllocBlock next; /* next block in aset's blocks list, if any */ char *freeptr; /* start of free space in this block */ char *endptr; /* end of space in this block */ +#ifdef MEMORY_CONTEXT_CHECKING + AllocSet aset; /* aset that owns this block */ +#endif } AllocBlockData; /* @@ -485,11 +487,13 @@ AllocSetContextCreateInternal(MemoryContext parent, /* Fill in the initial block's block header */ block = (AllocBlock) (((char *) set) + MAXALIGN(sizeof(AllocSetContext))); - block->aset = set; block->freeptr = ((char *) block) + ALLOC_BLOCKHDRSZ; block->endptr = ((char *) set) + firstBlockSize; block->prev = NULL; block->next = NULL; +#ifdef MEMORY_CONTEXT_CHECKING + block->aset = set; +#endif /* Mark unallocated space NOACCESS; leave the block header alone. */ VALGRIND_MAKE_MEM_NOACCESS(block->freeptr, block->endptr - block->freeptr); @@ -743,8 +747,10 @@ AllocSetAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; - block->aset = set; block->freeptr = block->endptr = ((char *) block) + blksize; +#ifdef MEMORY_CONTEXT_CHECKING + block->aset = set; +#endif chunk = (AllocChunk) (((char *) block) + ALLOC_BLOCKHDRSZ); chunk->aset = set; @@ -936,9 +942,11 @@ AllocSetAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; - block->aset = set; block->freeptr = ((char *) block) + ALLOC_BLOCKHDRSZ; block->endptr = ((char *) block) + blksize; +#ifdef MEMORY_CONTEXT_CHECKING + block->aset = set; +#endif /* Mark unallocated space NOACCESS. */ VALGRIND_MAKE_MEM_NOACCESS(block->freeptr, @@ -1019,8 +1027,10 @@ AllocSetFree(MemoryContext context, void *pointer) * reference the correct aset, and freeptr and endptr should point * just past the chunk. */ - if (block->aset != set || - block->freeptr != block->endptr || + if (block->freeptr != block->endptr || +#ifdef MEMORY_CONTEXT_CHECKING + block->aset != set || +#endif block->freeptr != ((char *) block) + (chunk->size + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) elog(ERROR, "could not find block containing chunk %p", chunk); @@ -1108,8 +1118,10 @@ AllocSetRealloc(MemoryContext context, void *pointer, Size size) * reference the correct aset, and freeptr and endptr should point * just past the chunk. */ - if (block->aset != set || - block->freeptr != block->endptr || + if (block->freeptr != block->endptr || +#ifdef MEMORY_CONTEXT_CHECKING + block->aset != set || +#endif block->freeptr != ((char *) block) + (oldsize + ALLOC_BLOCKHDRSZ + ALLOC_CHUNKHDRSZ)) elog(ERROR, "could not find block containing chunk %p", chunk); diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index e530e272e0..55acc2b84c 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -42,6 +42,7 @@ #define Generation_BLOCKHDRSZ MAXALIGN(sizeof(GenerationBlock)) +#define Generation_CHUNKSIZEZ SIZEOF_SIZE_T #define Generation_CHUNKHDRSZ sizeof(GenerationChunk) #define Generation_CHUNK_FRACTION 8 @@ -89,7 +90,6 @@ typedef struct GenerationContext struct GenerationBlock { dlist_node node; /* doubly-linked list of blocks */ - Size blksize; /* allocated size of this block */ int nchunks; /* number of chunks in the block */ int nfree; /* number of free chunks */ char *freeptr; /* start of free space in this block */ @@ -110,16 +110,17 @@ struct GenerationBlock */ struct GenerationChunk { +#ifdef MEMORY_CONTEXT_CHECKING /* size is always the size of the usable space in the chunk */ Size size; -#ifdef MEMORY_CONTEXT_CHECKING + /* when debugging memory usage, also store actual requested size */ /* this is zero in a free chunk */ Size requested_size; #define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T * 2 + SIZEOF_VOID_P * 2) #else -#define GENERATIONCHUNK_RAWSIZE (SIZEOF_SIZE_T + SIZEOF_VOID_P * 2) +#define GENERATIONCHUNK_RAWSIZE (SIZEOF_VOID_P * 2) #endif /* MEMORY_CONTEXT_CHECKING */ /* ensure proper alignment by adding padding if needed */ @@ -247,7 +248,7 @@ GenerationContextCreate(MemoryContext parent, /* Determine size of initial block */ allocSize = MAXALIGN(sizeof(GenerationContext)) + - Generation_BLOCKHDRSZ + Generation_CHUNKHDRSZ; + Generation_BLOCKHDRSZ + Generation_CHUNKHDRSZ + Generation_CHUNKSIZEZ; if (minContextSize != 0) allocSize = Max(allocSize, minContextSize); else @@ -303,8 +304,8 @@ GenerationContextCreate(MemoryContext parent, * Follows similar ideas as AllocSet, see aset.c for details ... */ set->allocChunkLimit = maxBlockSize; - while ((Size) (set->allocChunkLimit + Generation_CHUNKHDRSZ) > - (Size) ((Size) (maxBlockSize - Generation_BLOCKHDRSZ) / Generation_CHUNK_FRACTION)) + while ((Size) (set->allocChunkLimit + Generation_CHUNKHDRSZ + Generation_CHUNKSIZEZ) > + (Size) ((Size) (maxBlockSize - Generation_BLOCKHDRSZ + Generation_CHUNKSIZEZ) / Generation_CHUNK_FRACTION)) set->allocChunkLimit >>= 1; /* Finally, do the type-independent part of context creation */ @@ -399,8 +400,9 @@ GenerationAlloc(MemoryContext context, Size size) GenerationContext *set = (GenerationContext *) context; GenerationBlock *block; GenerationChunk *chunk; + char *ptr; Size chunk_size = MAXALIGN(size); - Size required_size = chunk_size + Generation_CHUNKHDRSZ; + Size required_size = chunk_size + Generation_CHUNKHDRSZ + Generation_CHUNKSIZEZ; /* is it an over-sized chunk? if yes, allocate special block */ if (chunk_size > set->allocChunkLimit) @@ -414,19 +416,22 @@ GenerationAlloc(MemoryContext context, Size size) context->mem_allocated += blksize; /* block with a single (used) chunk */ - block->blksize = blksize; block->nchunks = 1; block->nfree = 0; /* the block is completely full */ block->freeptr = block->endptr = ((char *) block) + blksize; - chunk = (GenerationChunk *) (((char *) block) + Generation_BLOCKHDRSZ); + /* Store chunk size outside chunk header */ + ptr = (((char *) block) + Generation_BLOCKHDRSZ); + memcpy(ptr, &chunk_size, Generation_CHUNKSIZEZ); + + chunk = (GenerationChunk *) (((char *) block) + Generation_BLOCKHDRSZ + Generation_CHUNKSIZEZ); chunk->block = block; chunk->context = set; - chunk->size = chunk_size; #ifdef MEMORY_CONTEXT_CHECKING + chunk->size = chunk_size; chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk_size) @@ -531,23 +536,27 @@ GenerationAlloc(MemoryContext context, Size size) /* we're supposed to have a block with enough free space now */ Assert(block != NULL); - Assert((block->endptr - block->freeptr) >= Generation_CHUNKHDRSZ + chunk_size); + Assert((block->endptr - block->freeptr) >= Generation_CHUNKHDRSZ + Generation_CHUNKSIZEZ + chunk_size); - chunk = (GenerationChunk *) block->freeptr; + /* Store chunk size outside chunk header */ + ptr = block->freeptr; + memcpy(ptr, &chunk_size, Generation_CHUNKSIZEZ); + + chunk = (GenerationChunk *) (block->freeptr + Generation_CHUNKSIZEZ); /* Prepare to initialize the chunk header. */ VALGRIND_MAKE_MEM_UNDEFINED(chunk, Generation_CHUNKHDRSZ); block->nchunks += 1; - block->freeptr += (Generation_CHUNKHDRSZ + chunk_size); + block->freeptr += (Generation_CHUNKSIZEZ + Generation_CHUNKHDRSZ + chunk_size); Assert(block->freeptr <= block->endptr); chunk->block = block; chunk->context = set; - chunk->size = chunk_size; #ifdef MEMORY_CONTEXT_CHECKING + chunk->size = chunk_size; chunk->requested_size = size; /* set mark to catch clobber of "unused" space */ if (size < chunk->size) @@ -576,7 +585,6 @@ GenerationAlloc(MemoryContext context, Size size) static inline void GenerationBlockInit(GenerationBlock *block, Size blksize) { - block->blksize = blksize; block->nchunks = 0; block->nfree = 0; @@ -647,10 +655,10 @@ GenerationBlockFree(GenerationContext *set, GenerationBlock *block) /* release the block from the list of blocks */ dlist_delete(&block->node); - ((MemoryContext) set)->mem_allocated -= block->blksize; + ((MemoryContext) set)->mem_allocated -= block->endptr - ((char *) block); #ifdef CLOBBER_FREED_MEMORY - wipe_mem(block, block->blksize); + wipe_mem(block, block->endptr - ((char *) block)); #endif free(block); @@ -672,6 +680,8 @@ GenerationFree(MemoryContext context, void *pointer) VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); block = chunk->block; + elog(LOG, "MAXALIGN(sizeof(GenerationContext))=%zu Generation_BLOCKHDRSZ=%zu Generation_CHUNKHDRSZ=%zu", + MAXALIGN(sizeof(GenerationContext)), Generation_BLOCKHDRSZ, Generation_CHUNKHDRSZ); #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ @@ -732,7 +742,7 @@ GenerationFree(MemoryContext context, void *pointer) */ dlist_delete(&block->node); - context->mem_allocated -= block->blksize; + context->mem_allocated -= block->endptr - ((char *) block); free(block); } @@ -753,9 +763,14 @@ GenerationRealloc(MemoryContext context, void *pointer, Size size) /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - oldsize = chunk->size; + /* Read chunk size outside chunk header */ + memcpy((char *) &oldsize, ((char *) chunk) - Generation_CHUNKSIZEZ, Generation_CHUNKSIZEZ); #ifdef MEMORY_CONTEXT_CHECKING + if (oldsize != chunk->size) + elog(WARNING, "detected wrong chunk size %s %p", + ((MemoryContext) set)->name, chunk); + /* Test for someone scribbling on unused space in chunk */ if (chunk->requested_size < oldsize) if (!sentinel_ok(pointer, chunk->requested_size)) @@ -862,12 +877,21 @@ static Size GenerationGetChunkSpace(MemoryContext context, void *pointer) { GenerationChunk *chunk = GenerationPointerGetChunk(pointer); - Size result; + Size size; + + /* Read chunk size outside chunk header */ + memcpy((char *) &size, ((char *) chunk) - Generation_CHUNKSIZEZ, Generation_CHUNKSIZEZ); + +#ifdef MEMORY_CONTEXT_CHECKING + if (size != chunk->size) + elog(WARNING, "detected wrong chunk size %s %p", + ((MemoryContext) set)->name, chunk); +#endif VALGRIND_MAKE_MEM_DEFINED(chunk, GENERATIONCHUNK_PRIVATE_LEN); - result = chunk->size + Generation_CHUNKHDRSZ; + size += Generation_CHUNKHDRSZ + Generation_CHUNKSIZEZ; VALGRIND_MAKE_MEM_NOACCESS(chunk, GENERATIONCHUNK_PRIVATE_LEN); - return result; + return size; } /* @@ -926,7 +950,7 @@ GenerationStats(MemoryContext context, nblocks++; nchunks += block->nchunks; nfreechunks += block->nfree; - totalspace += block->blksize; + totalspace += block->endptr - ((char *) block); freespace += (block->endptr - block->freeptr); } @@ -977,7 +1001,7 @@ GenerationCheck(MemoryContext context) nchunks; char *ptr; - total_allocated += block->blksize; + total_allocated += block->endptr - ((char *) block); /* * nfree > nchunks is surely wrong. Equality is allowed as the block
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-04 08:35  David Rowley <dgrowleyml@gmail.com>
  parent: Ranier Vilela <ranier.vf@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-10-04 08:35 UTC (permalink / raw)
  To: Ranier Vilela <ranier.vf@gmail.com>; +Cc: pgsql-hackers; Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>

On Tue, 4 Oct 2022 at 13:35, Ranier Vilela <ranier.vf@gmail.com> wrote:
> Revisiting my work on reducing memory consumption, I found this patch left out.
> I'm not sure I can help.
> But basically I was able to write and read the block size, in the chunk.
> Could it be the case of writing and reading the context pointer in the same way?
> Sure this leads to some performance loss, but would it make it possible to get the context pointer from the chunk?
> In other words, would it be possible to save the context pointer and compare it later in MemoryContextContains?

I'm not really sure I understand the intention of the patch. The
header size for all our memory contexts was already reduced in
c6e0fe1f2.  The patch you sent seems to pre-date that commit.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-04 11:29  Ranier Vilela <ranier.vf@gmail.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: Ranier Vilela @ 2022-10-04 11:29 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: pgsql-hackers; Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>

Em ter., 4 de out. de 2022 às 05:36, David Rowley <dgrowleyml@gmail.com>
escreveu:

> On Tue, 4 Oct 2022 at 13:35, Ranier Vilela <ranier.vf@gmail.com> wrote:
> > Revisiting my work on reducing memory consumption, I found this patch
> left out.
> > I'm not sure I can help.
> > But basically I was able to write and read the block size, in the chunk.
> > Could it be the case of writing and reading the context pointer in the
> same way?
> > Sure this leads to some performance loss, but would it make it possible
> to get the context pointer from the chunk?
> > In other words, would it be possible to save the context pointer and
> compare it later in MemoryContextContains?
>
> I'm not really sure I understand the intention of the patch. The
> header size for all our memory contexts was already reduced in
> c6e0fe1f2.  The patch you sent seems to pre-date that commit.
>
There is zero intention to commit this. It's just an experiment I did.

As it is in the patch, it is possible to save the context pointer outside
the header chunk.
Making it possible to retrieve it in MemoryContextContains.

It's just an idea.

regards,
Ranier Vilela

^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-04 12:25  Ranier Vilela <ranier.vf@gmail.com>
  parent: Ranier Vilela <ranier.vf@gmail.com>
  0 siblings, 0 replies; 152+ messages in thread

From: Ranier Vilela @ 2022-10-04 12:25 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: pgsql-hackers; Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>

Em ter., 4 de out. de 2022 às 08:29, Ranier Vilela <ranier.vf@gmail.com>
escreveu:

> Em ter., 4 de out. de 2022 às 05:36, David Rowley <dgrowleyml@gmail.com>
> escreveu:
>
>> On Tue, 4 Oct 2022 at 13:35, Ranier Vilela <ranier.vf@gmail.com> wrote:
>> > Revisiting my work on reducing memory consumption, I found this patch
>> left out.
>> > I'm not sure I can help.
>> > But basically I was able to write and read the block size, in the chunk.
>> > Could it be the case of writing and reading the context pointer in the
>> same way?
>> > Sure this leads to some performance loss, but would it make it possible
>> to get the context pointer from the chunk?
>> > In other words, would it be possible to save the context pointer and
>> compare it later in MemoryContextContains?
>>
>> I'm not really sure I understand the intention of the patch. The
>> header size for all our memory contexts was already reduced in
>> c6e0fe1f2.  The patch you sent seems to pre-date that commit.
>>
> There is zero intention to commit this. It's just an experiment I did.
>
> As it is in the patch, it is possible to save the context pointer outside
> the header chunk.
> Making it possible to retrieve it in MemoryContextContains.
>
Never mind, it's a waste of time.

regards,
Ranier Vilela

^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-04 15:55  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-10-04 15:55 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

I wrote:
> I think what we should look at is extending the aggregate/window
> function APIs so that such functions can report where they put their
> output, and then we can nuke MemoryContextContains(), with the
> code code set up to assume that it has to copy if the called function
> didn't report anything.  The existing FunctionCallInfo.resultinfo
> mechanism (cf. ReturnSetInfo for SRFs) is probably the right thing
> to pass the flag through.

After studying the existing usages of MemoryContextContains, I think
there is a better answer, which is to just nuke them.

As far as I can tell, the datumCopy steps associated with aggregate
finalfns are basically useless.  They only serve to prevent
returning a pointer directly to the aggregate's transition value
(or, perhaps, to a portion thereof).  But what's wrong with that?
It'll last as long as we need it to.  Maybe there was a reason
back before we required finalfns to not scribble on the transition
values, but those days are gone.

The same goes for aggregate serialfns --- although there, I can't
avoid the feeling that the datumCopy step was just cargo-culted in.
I don't think there can exist a serialfn that doesn't return a
freshly-palloced bytea.

The one place where we actually need the conditional datumCopy is
with window functions, and even there I don't think we need it
in simple cases with only one window function.  The case that is
hazardous is where multiple window functions are sharing a
WindowObject.  So I'm content to optimize the single-window-function
case and just always copy if there's more than one.  (Sadly, there
is no existing regression test that catches this, so I added one.)

See attached.

			regards, tom lane

Attachments: download all (2 files, .tar.gz)

0001-remove-MemoryContextContains-usages.patch (text/x-diff, 5.6K) download diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c index fe74e49814..45fcd37253 100644 --- a/src/backend/executor/nodeAgg.c +++ b/src/backend/executor/nodeAgg.c @@ -1028,6 +1028,8 @@ process_ordered_aggregate_multi(AggState *aggstate, * * The finalfn will be run, and the result delivered, in the * output-tuple context; caller's CurrentMemoryContext does not matter. + * (But note that in some cases, such as when there is no finalfn, the + * result might be a pointer to or into the agg's transition value.) * * The finalfn uses the state as set in the transno. This also might be * being used by another aggregate function, so it's important that we do @@ -1112,21 +1114,13 @@ finalize_aggregate(AggState *aggstate, } else { - /* Don't need MakeExpandedObjectReadOnly; datumCopy will copy it */ - *resultVal = pergroupstate->transValue; + *resultVal = + MakeExpandedObjectReadOnly(pergroupstate->transValue, + pergroupstate->transValueIsNull, + pertrans->transtypeLen); *resultIsNull = pergroupstate->transValueIsNull; } - /* - * If result is pass-by-ref, make sure it is in the right context. - */ - if (!peragg->resulttypeByVal && !*resultIsNull && - !MemoryContextContains(CurrentMemoryContext, - DatumGetPointer(*resultVal))) - *resultVal = datumCopy(*resultVal, - peragg->resulttypeByVal, - peragg->resulttypeLen); - MemoryContextSwitchTo(oldContext); } @@ -1176,19 +1170,13 @@ finalize_partialaggregate(AggState *aggstate, } else { - /* Don't need MakeExpandedObjectReadOnly; datumCopy will copy it */ - *resultVal = pergroupstate->transValue; + *resultVal = + MakeExpandedObjectReadOnly(pergroupstate->transValue, + pergroupstate->transValueIsNull, + pertrans->transtypeLen); *resultIsNull = pergroupstate->transValueIsNull; } - /* If result is pass-by-ref, make sure it is in the right context. */ - if (!peragg->resulttypeByVal && !*resultIsNull && - !MemoryContextContains(CurrentMemoryContext, - DatumGetPointer(*resultVal))) - *resultVal = datumCopy(*resultVal, - peragg->resulttypeByVal, - peragg->resulttypeLen); - MemoryContextSwitchTo(oldContext); } diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c index 8b0858e9f5..ce860bceeb 100644 --- a/src/backend/executor/nodeWindowAgg.c +++ b/src/backend/executor/nodeWindowAgg.c @@ -630,20 +630,13 @@ finalize_windowaggregate(WindowAggState *winstate, } else { - /* Don't need MakeExpandedObjectReadOnly; datumCopy will copy it */ - *result = peraggstate->transValue; + *result = + MakeExpandedObjectReadOnly(peraggstate->transValue, + peraggstate->transValueIsNull, + peraggstate->transtypeLen); *isnull = peraggstate->transValueIsNull; } - /* - * If result is pass-by-ref, make sure it is in the right context. - */ - if (!peraggstate->resulttypeByVal && !*isnull && - !MemoryContextContains(CurrentMemoryContext, - DatumGetPointer(*result))) - *result = datumCopy(*result, - peraggstate->resulttypeByVal, - peraggstate->resulttypeLen); MemoryContextSwitchTo(oldContext); } @@ -1057,13 +1050,14 @@ eval_windowfunction(WindowAggState *winstate, WindowStatePerFunc perfuncstate, *isnull = fcinfo->isnull; /* - * Make sure pass-by-ref data is allocated in the appropriate context. (We - * need this in case the function returns a pointer into some short-lived - * tuple, as is entirely possible.) + * The window function might have returned a pass-by-ref result that's + * just a pointer into one of the WindowObject's temporary slots. That's + * not a problem if it's the only window function using the WindowObject; + * but if there's more than one function, we'd better copy the result to + * ensure it's not clobbered by later window functions. */ if (!perfuncstate->resulttypeByVal && !fcinfo->isnull && - !MemoryContextContains(CurrentMemoryContext, - DatumGetPointer(*result))) + winstate->numfuncs > 1) *result = datumCopy(*result, perfuncstate->resulttypeByVal, perfuncstate->resulttypeLen); diff --git a/src/test/regress/expected/window.out b/src/test/regress/expected/window.out index 55dcd668c9..170bea23c2 100644 --- a/src/test/regress/expected/window.out +++ b/src/test/regress/expected/window.out @@ -657,6 +657,23 @@ select first_value(max(x)) over (), y -> Seq Scan on tenk1 (4 rows) +-- window functions returning pass-by-ref values from different rows +select x, lag(x, 1) over (order by x), lead(x, 3) over (order by x) +from (select x::numeric as x from generate_series(1,10) x); + x | lag | lead +----+-----+------ + 1 | | 4 + 2 | 1 | 5 + 3 | 2 | 6 + 4 | 3 | 7 + 5 | 4 | 8 + 6 | 5 | 9 + 7 | 6 | 10 + 8 | 7 | + 9 | 8 | + 10 | 9 | +(10 rows) + -- test non-default frame specifications SELECT four, ten, sum(ten) over (partition by four order by ten), diff --git a/src/test/regress/sql/window.sql b/src/test/regress/sql/window.sql index 57c39e796c..1138453131 100644 --- a/src/test/regress/sql/window.sql +++ b/src/test/regress/sql/window.sql @@ -153,6 +153,10 @@ select first_value(max(x)) over (), y from (select unique1 as x, ten+four as y from tenk1) ss group by y; +-- window functions returning pass-by-ref values from different rows +select x, lag(x, 1) over (order by x), lead(x, 3) over (order by x) +from (select x::numeric as x from generate_series(1,10) x); + -- test non-default frame specifications SELECT four, ten, sum(ten) over (partition by four order by ten),
0002-remove-MemoryContextContains.patch (text/x-diff, 3.3K) download diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index 115a64cfe4..c80236d285 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -224,10 +224,8 @@ MemoryContextResetOnly(MemoryContext context) * If context->ident points into the context's memory, it will become * a dangling pointer. We could prevent that by setting it to NULL * here, but that would break valid coding patterns that keep the - * ident elsewhere, e.g. in a parent context. Another idea is to use - * MemoryContextContains(), but we don't require ident strings to be - * in separately-palloc'd chunks, so that risks false positives. So - * for now we assume the programmer got it right. + * ident elsewhere, e.g. in a parent context. So for now we assume + * the programmer got it right. */ context->methods->reset(context); @@ -482,15 +480,6 @@ MemoryContextAllowInCriticalSection(MemoryContext context, bool allow) MemoryContext GetMemoryChunkContext(void *pointer) { - /* - * Try to detect bogus pointers handed to us, poorly though we can. - * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an - * allocated chunk. - */ - Assert(pointer != NULL); - Assert(pointer == (void *) MAXALIGN(pointer)); - /* adding further Asserts here? See pre-checks in MemoryContextContains */ - return MCXT_METHOD(pointer, get_chunk_context) (pointer); } @@ -813,49 +802,6 @@ MemoryContextCheck(MemoryContext context) } #endif -/* - * MemoryContextContains - * Detect whether an allocated chunk of memory belongs to a given - * context or not. - * - * Caution: 'pointer' must point to a pointer which was allocated by a - * MemoryContext. It's not safe or valid to use this function on arbitrary - * pointers as obtaining the MemoryContext which 'pointer' belongs to requires - * possibly several pointer dereferences. - */ -bool -MemoryContextContains(MemoryContext context, void *pointer) -{ - /* - * Temporarily make this always return false as we don't yet have a fully - * baked idea on how to make it work correctly with the new MemoryChunk - * code. - */ - return false; - -#ifdef NOT_USED - MemoryContext ptr_context; - - /* - * NB: We must perform run-time checks here which GetMemoryChunkContext() - * does as assertions before calling GetMemoryChunkContext(). - * - * Try to detect bogus pointers handed to us, poorly though we can. - * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an - * allocated chunk. - */ - if (pointer == NULL || pointer != (void *) MAXALIGN(pointer)) - return false; - - /* - * OK, it's probably safe to look at the context. - */ - ptr_context = GetMemoryChunkContext(pointer); - - return ptr_context == context; -#endif -} - /* * MemoryContextCreate * Context-type-independent part of context creation. diff --git a/src/include/utils/memutils.h b/src/include/utils/memutils.h index 52bc41ec53..4f6c5435ca 100644 --- a/src/include/utils/memutils.h +++ b/src/include/utils/memutils.h @@ -96,7 +96,6 @@ extern void MemoryContextAllowInCriticalSection(MemoryContext context, #ifdef MEMORY_CONTEXT_CHECKING extern void MemoryContextCheck(MemoryContext context); #endif -extern bool MemoryContextContains(MemoryContext context, void *pointer); /* Handy macro for copying and assigning context ID ... but note double eval */ #define MemoryContextCopyAndSetIdentifier(cxt, id) \
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-06 04:59  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 2 replies; 152+ messages in thread

From: David Rowley @ 2022-10-06 04:59 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Wed, 5 Oct 2022 at 04:55, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> After studying the existing usages of MemoryContextContains, I think
> there is a better answer, which is to just nuke them.

I was under the impression you wanted to keep that function around in
cassert builds for some of the guc.c changes you were making.

> As far as I can tell, the datumCopy steps associated with aggregate
> finalfns are basically useless.  They only serve to prevent
> returning a pointer directly to the aggregate's transition value
> (or, perhaps, to a portion thereof).  But what's wrong with that?
> It'll last as long as we need it to.  Maybe there was a reason
> back before we required finalfns to not scribble on the transition
> values, but those days are gone.

Yeah, I wondered the same thing. I couldn't see a situation where the
aggregate context would disappear.

> The same goes for aggregate serialfns --- although there, I can't
> avoid the feeling that the datumCopy step was just cargo-culted in.
> I don't think there can exist a serialfn that doesn't return a
> freshly-palloced bytea.

Most likely. I probably copied that as I wouldn't have understood why
we did any copying when calling the finalfn. I still don't understand
why. Seems there's no good reason if we're both in favour of removing
it.

> The one place where we actually need the conditional datumCopy is
> with window functions, and even there I don't think we need it
> in simple cases with only one window function.  The case that is
> hazardous is where multiple window functions are sharing a
> WindowObject.  So I'm content to optimize the single-window-function
> case and just always copy if there's more than one.  (Sadly, there
> is no existing regression test that catches this, so I added one.)

I was unsure what window functions might exist out in the wild, so I'd
added some code to pass along the return type information so that any
extensions which need to make a copy can do so.  However, maybe it's
better just to wait to see if anyone complains about that before we go
to the trouble.

I've looked at your patches and don't see any problems. Our findings
seem to be roughly the same. i.e the datumCopy is mostly useless.
However, you've noticed the requirement to datumCopy when there are
multiple window functions using the same window along with yours
containing the call to MakeExpandedObjectReadOnly() where I missed
that.

This should also slightly improve the performance of LEAD and LAG with
byref types, which seems like a good side-effect.

I guess the commit message for 0002 should mention that for pointers
to allocated chunks that GetMemoryChunkContext() can be used in place
of MemoryContextContains(). I did see that PostGIS does use
MemoryContextContains(), though I didn't look at their code to figure
out if they're always passing it a pointer to an allocated chunk.
Maybe it's worth doing;

#define MemoryContextContains(c, p) (GetMemoryChunkContext(p) == (c))

in memutils.h? or are we better to force extension authors to
re-evaluate their code in case anyone is passing memory that's not
pointing directly to a palloc'd chunk?

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-06 15:37  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 0 replies; 152+ messages in thread

From: Tom Lane @ 2022-10-06 15:37 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> On Wed, 5 Oct 2022 at 04:55, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> After studying the existing usages of MemoryContextContains, I think
>> there is a better answer, which is to just nuke them.

> I was under the impression you wanted to keep that function around in
> cassert builds for some of the guc.c changes you were making.

I would've liked to have it, but for that purpose an unreliable version
of MemoryContextContains is probably little help.  In any case, as you
mention, I can do something with GetMemoryChunkContext() instead.

>> As far as I can tell, the datumCopy steps associated with aggregate
>> finalfns are basically useless.  They only serve to prevent
>> returning a pointer directly to the aggregate's transition value
>> (or, perhaps, to a portion thereof).  But what's wrong with that?
>> It'll last as long as we need it to.  Maybe there was a reason
>> back before we required finalfns to not scribble on the transition
>> values, but those days are gone.

> Yeah, I wondered the same thing. I couldn't see a situation where the
> aggregate context would disappear.

I have a feeling that we might once have aggressively reset the
aggregate context ... but we don't anymore.

>> The one place where we actually need the conditional datumCopy is
>> with window functions, and even there I don't think we need it
>> in simple cases with only one window function.  The case that is
>> hazardous is where multiple window functions are sharing a
>> WindowObject.  So I'm content to optimize the single-window-function
>> case and just always copy if there's more than one.  (Sadly, there
>> is no existing regression test that catches this, so I added one.)

> I was unsure what window functions might exist out in the wild, so I'd
> added some code to pass along the return type information so that any
> extensions which need to make a copy can do so.  However, maybe it's
> better just to wait to see if anyone complains about that before we go
> to the trouble.

I'd originally feared that a window function might return a pointer
into the WindowObject's tuplestore, which we manipulate immediately
after the window function returns.  However, AFAICS the APIs we
provide don't have any such hazard.  The actual hazard is that we
might get a pointer into one of the temp slots, which are independent
storage because we tell them to copy the source tuple.  (Maybe a comment
about that would be appropriate.)

> I've looked at your patches and don't see any problems. Our findings
> seem to be roughly the same. i.e the datumCopy is mostly useless.

Cool, I'll push in a little bit.

> Maybe it's worth doing;

> #define MemoryContextContains(c, p) (GetMemoryChunkContext(p) == (c))

> in memutils.h? or are we better to force extension authors to
> re-evaluate their code in case anyone is passing memory that's not
> pointing directly to a palloc'd chunk?

I think the latter.  The fact that MemoryContextContains was (mostly)
safe on arbitrary pointers was an important part of its API IMO.
I'm okay with giving up that property to reduce chunk overhead,
but we'll do nobody any service by pretending we still have it.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-06 17:38  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-10-06 17:38 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> I did see that PostGIS does use
> MemoryContextContains(), though I didn't look at their code to figure
> out if they're always passing it a pointer to an allocated chunk.

As far as I can tell from a cursory look, they should be able to use
the GetMemoryChunkContext workaround, because they are just doing this
with SHARED_GSERIALIZED objects, which seem to always be palloc'd.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-06 18:19  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-10-06 18:19 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

One more thing: based on what I saw in working with my pending guc.c
changes, the assertions in GetMemoryChunkMethodID are largely useless
for detecting bogus pointers.  I think we should do something more
like the attached, which will result in a clean failure if the method
ID bits are invalid.

I'm a little tempted also to rearrange the MemoryContextMethodID enum
so that likely bit patterns like 000 are not valid IDs.

While I didn't change it here, I wonder why GetMemoryChunkMethodID is
publicly exposed at all.  AFAICS it could be static inside mcxt.c.

			regards, tom lane

Attachments:

more-mcxt-robustness-1.patch (text/x-diff, 4.9K) download diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index c80236d285..e82d9b21ba 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -32,6 +32,11 @@ #include "utils/memutils_internal.h" +static void BogusFree(void *pointer); +static void *BogusRealloc(void *pointer, Size size); +static MemoryContext BogusGetChunkContext(void *pointer); +static Size BogusGetChunkSpace(void *pointer); + /***************************************************************************** * GLOBAL MEMORY * *****************************************************************************/ @@ -74,10 +79,42 @@ static const MemoryContextMethods mcxt_methods[] = { [MCTX_SLAB_ID].get_chunk_context = SlabGetChunkContext, [MCTX_SLAB_ID].get_chunk_space = SlabGetChunkSpace, [MCTX_SLAB_ID].is_empty = SlabIsEmpty, - [MCTX_SLAB_ID].stats = SlabStats + [MCTX_SLAB_ID].stats = SlabStats, #ifdef MEMORY_CONTEXT_CHECKING - ,[MCTX_SLAB_ID].check = SlabCheck + [MCTX_SLAB_ID].check = SlabCheck, #endif + + /* + * Unused (as yet) IDs should have dummy entries here. This allows us to + * fail cleanly if a bogus pointer is passed to pfree or the like. It + * seems sufficient to provide routines for the methods that might get + * invoked from inspection of a chunk (see MCXT_METHOD calls below). + */ + + [MCTX_UNUSED3_ID].free_p = BogusFree, + [MCTX_UNUSED3_ID].realloc = BogusRealloc, + [MCTX_UNUSED3_ID].get_chunk_context = BogusGetChunkContext, + [MCTX_UNUSED3_ID].get_chunk_space = BogusGetChunkSpace, + + [MCTX_UNUSED4_ID].free_p = BogusFree, + [MCTX_UNUSED4_ID].realloc = BogusRealloc, + [MCTX_UNUSED4_ID].get_chunk_context = BogusGetChunkContext, + [MCTX_UNUSED4_ID].get_chunk_space = BogusGetChunkSpace, + + [MCTX_UNUSED5_ID].free_p = BogusFree, + [MCTX_UNUSED5_ID].realloc = BogusRealloc, + [MCTX_UNUSED5_ID].get_chunk_context = BogusGetChunkContext, + [MCTX_UNUSED5_ID].get_chunk_space = BogusGetChunkSpace, + + [MCTX_UNUSED6_ID].free_p = BogusFree, + [MCTX_UNUSED6_ID].realloc = BogusRealloc, + [MCTX_UNUSED6_ID].get_chunk_context = BogusGetChunkContext, + [MCTX_UNUSED6_ID].get_chunk_space = BogusGetChunkSpace, + + [MCTX_UNUSED7_ID].free_p = BogusFree, + [MCTX_UNUSED7_ID].realloc = BogusRealloc, + [MCTX_UNUSED7_ID].get_chunk_context = BogusGetChunkContext, + [MCTX_UNUSED7_ID].get_chunk_space = BogusGetChunkSpace, }; /* @@ -125,6 +162,34 @@ static void MemoryContextStatsPrint(MemoryContext context, void *passthru, #define MCXT_METHOD(pointer, method) \ mcxt_methods[GetMemoryChunkMethodID(pointer)].method +/* + * Support routines to trap use of invalid memory context method IDs + * (from calling pfree or the like on a bogus pointer). + */ +static void +BogusFree(void *pointer) +{ + elog(ERROR, "pfree called with invalid pointer %p", pointer); +} + +static void * +BogusRealloc(void *pointer, Size size) +{ + elog(ERROR, "repalloc called with invalid pointer %p", pointer); +} + +static MemoryContext +BogusGetChunkContext(void *pointer) +{ + elog(ERROR, "GetMemoryChunkContext called with invalid pointer %p", pointer); +} + +static Size +BogusGetChunkSpace(void *pointer) +{ + elog(ERROR, "GetMemoryChunkSpace called with invalid pointer %p", pointer); +} + /***************************************************************************** * EXPORTED ROUTINES * diff --git a/src/include/utils/memutils_internal.h b/src/include/utils/memutils_internal.h index 377cee7a84..797409ee94 100644 --- a/src/include/utils/memutils_internal.h +++ b/src/include/utils/memutils_internal.h @@ -77,12 +77,20 @@ extern void SlabCheck(MemoryContext context); * The maximum value for this enum is constrained by * MEMORY_CONTEXT_METHODID_MASK. If an enum value higher than that is * required then MEMORY_CONTEXT_METHODID_BITS will need to be increased. + * For robustness, ensure that MemoryContextMethodID has a value for + * each possible bit-pattern of MEMORY_CONTEXT_METHODID_MASK, and make + * dummy entries for unused IDs in the mcxt_methods[] array. */ typedef enum MemoryContextMethodID { MCTX_ASET_ID, MCTX_GENERATION_ID, MCTX_SLAB_ID, + MCTX_UNUSED3_ID, + MCTX_UNUSED4_ID, + MCTX_UNUSED5_ID, + MCTX_UNUSED6_ID, + MCTX_UNUSED7_ID } MemoryContextMethodID; /* @@ -110,20 +118,11 @@ extern void MemoryContextCreate(MemoryContext node, * directly precedes 'pointer'. */ static inline MemoryContextMethodID -GetMemoryChunkMethodID(void *pointer) +GetMemoryChunkMethodID(const void *pointer) { uint64 header; - /* - * Try to detect bogus pointers handed to us, poorly though we can. - * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an - * allocated chunk. - */ - Assert(pointer != NULL); - Assert(pointer == (void *) MAXALIGN(pointer)); - - header = *((uint64 *) ((char *) pointer - sizeof(uint64))); - + header = *((const uint64 *) ((const char *) pointer - sizeof(uint64))); return (MemoryContextMethodID) (header & MEMORY_CONTEXT_METHODID_MASK); } =
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-06 19:00  Andres Freund <andres@anarazel.de>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: Andres Freund @ 2022-10-06 19:00 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: David Rowley <dgrowleyml@gmail.com>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2022-10-06 14:19:21 -0400, Tom Lane wrote:
> One more thing: based on what I saw in working with my pending guc.c
> changes, the assertions in GetMemoryChunkMethodID are largely useless
> for detecting bogus pointers.  I think we should do something more
> like the attached, which will result in a clean failure if the method
> ID bits are invalid.

Yea, that makes sense. I wouldn't get rid of the MAXALIGN Assert though - it's
not replaced by the the unused mcxt stuff afaics.


> I'm a little tempted also to rearrange the MemoryContextMethodID enum
> so that likely bit patterns like 000 are not valid IDs.

Yea, I was suggesting that during a review as well. We can still relax it
later if we run out of bits.


> +/*
> + * Support routines to trap use of invalid memory context method IDs
> + * (from calling pfree or the like on a bogus pointer).
> + */
> +static void
> +BogusFree(void *pointer)
> +{
> +	elog(ERROR, "pfree called with invalid pointer %p", pointer);
> +}

Maybe worth printing the method ID as well?

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-06 19:10  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-10-06 19:10 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: David Rowley <dgrowleyml@gmail.com>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Andres Freund <andres@anarazel.de> writes:
> Yea, that makes sense. I wouldn't get rid of the MAXALIGN Assert though - it's
> not replaced by the the unused mcxt stuff afaics.

OK.

>> +	elog(ERROR, "pfree called with invalid pointer %p", pointer);

> Maybe worth printing the method ID as well?

I doubt it'd be useful.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-06 19:14  Andres Freund <andres@anarazel.de>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: Andres Freund @ 2022-10-06 19:14 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: David Rowley <dgrowleyml@gmail.com>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2022-10-06 15:10:44 -0400, Tom Lane wrote:
> Andres Freund <andres@anarazel.de> writes:
> >> +	elog(ERROR, "pfree called with invalid pointer %p", pointer);
>
> > Maybe worth printing the method ID as well?
>
> I doubt it'd be useful.

I was thinking it could be useful to see whether the bits are likely to be the
result of wipe_mem(). But I guess for that we should print the whole byte,
rather than just the method. Perhaps not worth it.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-06 19:23  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-10-06 19:23 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: David Rowley <dgrowleyml@gmail.com>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Andres Freund <andres@anarazel.de> writes:
> On 2022-10-06 15:10:44 -0400, Tom Lane wrote:
>> Andres Freund <andres@anarazel.de> writes:
>>> Maybe worth printing the method ID as well?

>> I doubt it'd be useful.

> I was thinking it could be useful to see whether the bits are likely to be the
> result of wipe_mem(). But I guess for that we should print the whole byte,
> rather than just the method. Perhaps not worth it.

I think printing the whole int64 header word would be appropriate if
we were hoping for something like that.  Still not sure if it's useful.
On the other hand, if control gets there then you are probably in need
of debugging help ...

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-06 20:05  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 2 replies; 152+ messages in thread

From: Tom Lane @ 2022-10-06 20:05 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Here's a v2 incorporating discussed changes.

In reordering enum MemoryContextMethodID, I arranged to avoid using
000 and 111 as valid IDs, since those bit patterns will appear in
zeroed and wipe_mem'd memory respectively.  Those should probably be
more-or-less-permanent exclusions, so I added comments about it.

I also avoided using 001: based on my work with converting guc.c to use
palloc [1], it seems that pfree'ing a malloc-provided pointer is likely
to see 001 a lot, at least on 64-bit glibc platforms.  I've not stuck
my nose into the glibc sources to see how consistent that might be,
but it definitely recurred several times while I was chasing down
places needing adjustment in that patch.

I'm not sure if there are any platform-dependent reasons to avoid
other bit-patterns, but we do still have a little bit of flexibility
left here if anyone has candidates.

			regards, tom lane

[1] https://www.postgresql.org/message-id/2982579.1662416866%40sss.pgh.pa.us

Attachments:

more-mcxt-robustness-2.patch (text/x-diff, 6.8K) download diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index c80236d285..b1a3c74830 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -32,6 +32,11 @@ #include "utils/memutils_internal.h" +static void BogusFree(void *pointer); +static void *BogusRealloc(void *pointer, Size size); +static MemoryContext BogusGetChunkContext(void *pointer); +static Size BogusGetChunkSpace(void *pointer); + /***************************************************************************** * GLOBAL MEMORY * *****************************************************************************/ @@ -74,10 +79,42 @@ static const MemoryContextMethods mcxt_methods[] = { [MCTX_SLAB_ID].get_chunk_context = SlabGetChunkContext, [MCTX_SLAB_ID].get_chunk_space = SlabGetChunkSpace, [MCTX_SLAB_ID].is_empty = SlabIsEmpty, - [MCTX_SLAB_ID].stats = SlabStats + [MCTX_SLAB_ID].stats = SlabStats, #ifdef MEMORY_CONTEXT_CHECKING - ,[MCTX_SLAB_ID].check = SlabCheck + [MCTX_SLAB_ID].check = SlabCheck, #endif + + /* + * Unused (as yet) IDs should have dummy entries here. This allows us to + * fail cleanly if a bogus pointer is passed to pfree or the like. It + * seems sufficient to provide routines for the methods that might get + * invoked from inspection of a chunk (see MCXT_METHOD calls below). + */ + + [MCTX_UNUSED1_ID].free_p = BogusFree, + [MCTX_UNUSED1_ID].realloc = BogusRealloc, + [MCTX_UNUSED1_ID].get_chunk_context = BogusGetChunkContext, + [MCTX_UNUSED1_ID].get_chunk_space = BogusGetChunkSpace, + + [MCTX_UNUSED2_ID].free_p = BogusFree, + [MCTX_UNUSED2_ID].realloc = BogusRealloc, + [MCTX_UNUSED2_ID].get_chunk_context = BogusGetChunkContext, + [MCTX_UNUSED2_ID].get_chunk_space = BogusGetChunkSpace, + + [MCTX_UNUSED3_ID].free_p = BogusFree, + [MCTX_UNUSED3_ID].realloc = BogusRealloc, + [MCTX_UNUSED3_ID].get_chunk_context = BogusGetChunkContext, + [MCTX_UNUSED3_ID].get_chunk_space = BogusGetChunkSpace, + + [MCTX_UNUSED4_ID].free_p = BogusFree, + [MCTX_UNUSED4_ID].realloc = BogusRealloc, + [MCTX_UNUSED4_ID].get_chunk_context = BogusGetChunkContext, + [MCTX_UNUSED4_ID].get_chunk_space = BogusGetChunkSpace, + + [MCTX_UNUSED5_ID].free_p = BogusFree, + [MCTX_UNUSED5_ID].realloc = BogusRealloc, + [MCTX_UNUSED5_ID].get_chunk_context = BogusGetChunkContext, + [MCTX_UNUSED5_ID].get_chunk_space = BogusGetChunkSpace, }; /* @@ -125,6 +162,77 @@ static void MemoryContextStatsPrint(MemoryContext context, void *passthru, #define MCXT_METHOD(pointer, method) \ mcxt_methods[GetMemoryChunkMethodID(pointer)].method +/* + * GetMemoryChunkMethodID + * Return the MemoryContextMethodID from the uint64 chunk header which + * directly precedes 'pointer'. + */ +static inline MemoryContextMethodID +GetMemoryChunkMethodID(const void *pointer) +{ + uint64 header; + + /* + * Try to detect bogus pointers handed to us, poorly though we can. + * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an + * allocated chunk. + */ + Assert(pointer == (const void *) MAXALIGN(pointer)); + + header = *((const uint64 *) ((const char *) pointer - sizeof(uint64))); + + return (MemoryContextMethodID) (header & MEMORY_CONTEXT_METHODID_MASK); +} + +/* + * GetMemoryChunkHeader + * Return the uint64 chunk header which directly precedes 'pointer'. + * + * This is only used after GetMemoryChunkMethodID, so no need for error checks. + */ +static inline uint64 +GetMemoryChunkHeader(const void *pointer) +{ + return *((const uint64 *) ((const char *) pointer - sizeof(uint64))); +} + +/* + * Support routines to trap use of invalid memory context method IDs + * (from calling pfree or the like on a bogus pointer). As a possible + * aid in debugging, we report the header word along with the pointer + * address (if we got here, there must be an accessible header word). + */ +static void +BogusFree(void *pointer) +{ + elog(ERROR, "pfree called with invalid pointer %p (header 0x%016llx)", + pointer, (long long) GetMemoryChunkHeader(pointer)); +} + +static void * +BogusRealloc(void *pointer, Size size) +{ + elog(ERROR, "repalloc called with invalid pointer %p (header 0x%016llx)", + pointer, (long long) GetMemoryChunkHeader(pointer)); + return NULL; /* keep compiler quiet */ +} + +static MemoryContext +BogusGetChunkContext(void *pointer) +{ + elog(ERROR, "GetMemoryChunkContext called with invalid pointer %p (header 0x%016llx)", + pointer, (long long) GetMemoryChunkHeader(pointer)); + return NULL; /* keep compiler quiet */ +} + +static Size +BogusGetChunkSpace(void *pointer) +{ + elog(ERROR, "GetMemoryChunkSpace called with invalid pointer %p (header 0x%016llx)", + pointer, (long long) GetMemoryChunkHeader(pointer)); + return 0; /* keep compiler quiet */ +} + /***************************************************************************** * EXPORTED ROUTINES * diff --git a/src/include/utils/memutils_internal.h b/src/include/utils/memutils_internal.h index 377cee7a84..e90808dbea 100644 --- a/src/include/utils/memutils_internal.h +++ b/src/include/utils/memutils_internal.h @@ -74,15 +74,23 @@ extern void SlabCheck(MemoryContext context); * MemoryContextMethodID * A unique identifier for each MemoryContext implementation which * indicates the index into the mcxt_methods[] array. See mcxt.c. - * The maximum value for this enum is constrained by - * MEMORY_CONTEXT_METHODID_MASK. If an enum value higher than that is - * required then MEMORY_CONTEXT_METHODID_BITS will need to be increased. + * + * For robust error detection, ensure that MemoryContextMethodID has a value + * for each possible bit-pattern of MEMORY_CONTEXT_METHODID_MASK, and make + * dummy entries for unused IDs in the mcxt_methods[] array. We also try + * to avoid using bit-patterns as valid IDs if they are likely to occur in + * garbage data. */ typedef enum MemoryContextMethodID { + MCTX_UNUSED1_ID, /* avoid: 000 occurs in never-used memory */ + MCTX_UNUSED2_ID, MCTX_ASET_ID, MCTX_GENERATION_ID, MCTX_SLAB_ID, + MCTX_UNUSED3_ID, + MCTX_UNUSED4_ID, + MCTX_UNUSED5_ID /* avoid: 111 occurs in wipe_mem'd memory */ } MemoryContextMethodID; /* @@ -104,27 +112,4 @@ extern void MemoryContextCreate(MemoryContext node, MemoryContext parent, const char *name); -/* - * GetMemoryChunkMethodID - * Return the MemoryContextMethodID from the uint64 chunk header which - * directly precedes 'pointer'. - */ -static inline MemoryContextMethodID -GetMemoryChunkMethodID(void *pointer) -{ - uint64 header; - - /* - * Try to detect bogus pointers handed to us, poorly though we can. - * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an - * allocated chunk. - */ - Assert(pointer != NULL); - Assert(pointer == (void *) MAXALIGN(pointer)); - - header = *((uint64 *) ((char *) pointer - sizeof(uint64))); - - return (MemoryContextMethodID) (header & MEMORY_CONTEXT_METHODID_MASK); -} - #endif /* MEMUTILS_INTERNAL_H */
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-06 20:44  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-10-06 20:44 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Fri, 7 Oct 2022 at 09:05, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> Here's a v2 incorporating discussed changes.
>
> In reordering enum MemoryContextMethodID, I arranged to avoid using
> 000 and 111 as valid IDs, since those bit patterns will appear in
> zeroed and wipe_mem'd memory respectively.  Those should probably be
> more-or-less-permanent exclusions, so I added comments about it.

I'm just considering some future developer here that is writing a new
MemoryContext type and there's no more space left and she or he needs
to either use 000 or 111. I think if that was me, I might be unsure if
I should be looking to expand the bit-space to make room. I might
think that based on the word "avoid" in:

> + MCTX_UNUSED1_ID, /* avoid: 000 occurs in never-used memory */
> + MCTX_UNUSED5_ID /* avoid: 111 occurs in wipe_mem'd memory */

but the final sentence in:

> + * dummy entries for unused IDs in the mcxt_methods[] array.  We also try
> + * to avoid using bit-patterns as valid IDs if they are likely to occur in
> + * garbage data.

leads me to believe we're just *trying* to avoid using these bit-patterns.

Also, the comment in mcxt_methods[] might make me believe that it's ok
for me to use them if I really need to.

> + * Unused (as yet) IDs should have dummy entries here.  This allows us to

Based on these comments, I'm not quite sure if I should be completely
avoiding using 000 and 111 or I should just use those last when there
are no other free slots in the array. It might be quite a long time
before someone is in this situation, so should we be more clear?

However, maybe you've left it this way as you feel it's a decision
that must be made in the future, perhaps based on how difficult it
would be to free up another bit?

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-06 20:54  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 0 replies; 152+ messages in thread

From: Tom Lane @ 2022-10-06 20:54 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> However, maybe you've left it this way as you feel it's a decision
> that must be made in the future, perhaps based on how difficult it
> would be to free up another bit?

Yeah, pretty much.  I think it'll be a long time before we run out
of memory context IDs, and it's hard to anticipate the tradeoffs
that will matter at that time.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-06 21:57  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 2 replies; 152+ messages in thread

From: Tom Lane @ 2022-10-06 21:57 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

I wrote:
> I also avoided using 001: based on my work with converting guc.c to use
> palloc [1], it seems that pfree'ing a malloc-provided pointer is likely
> to see 001 a lot, at least on 64-bit glibc platforms.

I poked at this some more by creating a function that intentionally
does pfree(malloc(N)) for various values of N.

RHEL8, x86_64: the low-order nibble of the header is consistently 0001.

macOS 12.6, arm64: the low-order nibble is consistently 0000.

FreeBSD 13.0, arm64: Usually the low-order nibble is 0000 or 1111,
but for some smaller values of N it sometimes comes up as 0010.

NetBSD 9.2, amd64: results similar to FreeBSD.

I still haven't looked into anybody's source code, but based on these
results I'm inclined to leave both 001 and 010 IDs unused for now.
That'll help the GUC malloc -> palloc transition tremendously, because
people will get fairly clear errors rather than weird assertions
and/or memory corruption.  That'll leave us in a situation where only
one more context ID can be assigned without risk of reducing our error
detection ability, but I'm content with that for now.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-06 22:38  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 0 replies; 152+ messages in thread

From: David Rowley @ 2022-10-06 22:38 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Fri, 7 Oct 2022 at 10:57, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> I poked at this some more by creating a function that intentionally
> does pfree(malloc(N)) for various values of N.
>
> RHEL8, x86_64: the low-order nibble of the header is consistently 0001.
>
> macOS 12.6, arm64: the low-order nibble is consistently 0000.
>
> FreeBSD 13.0, arm64: Usually the low-order nibble is 0000 or 1111,
> but for some smaller values of N it sometimes comes up as 0010.
>
> NetBSD 9.2, amd64: results similar to FreeBSD.

Out of curiosity I tried using the attached on a Windows machine and got:

0: 130951
1: 131061
2: 133110
3: 129053
4: 131061
5: 131067
6: 131070
7: 131203

So it seems pretty much entirely inconsistent on that platform.

Also, on an Ubuntu machine I didn't get the consistent 0001 as you got
on your RHEL machine. There were a very small number of 010's there
too:

0: 0
1: 1048569
2: 7
3: 0
4: 0
5: 0
6: 0
7: 0

Despite Windows not being very consistent here, I think it's a useful
change as if our most common platform (Linux/glibc) is fairly
consistent, then that'll give us wide coverage to track down any buggy
code.

In anycase, even on Windows (assuming it's completely random) we'll
have a 5 out of 8 chance of getting a nice error message if there are
any bad pointers being passed.

David

Attachments:

malloc_ptr.c (text/plain, 454B) download #include <stdio.h> #include <stdlib.h> typedef unsigned long long uint64; int main(void) { size_t count[8] = {0}; size_t n; for (n = 0; n < 1024*1024; n++) { void *ptr = (void *) malloc(n); uint64 header; if (!ptr) { fprintf(stderr, "OOM\n"); return -1; } header = *((uint64 *) ((char *) ptr - sizeof(uint64))); count[header & 7]++; free(ptr); } for (n = 0; n <= 7; n++) printf("%zd: %zd\n", n, count[n]); return 0; }
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-06 23:10  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-10-06 23:10 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

I wrote:
> FreeBSD 13.0, arm64: Usually the low-order nibble is 0000 or 1111,
> but for some smaller values of N it sometimes comes up as 0010.
> NetBSD 9.2, amd64: results similar to FreeBSD.

I looked into NetBSD's malloc.c, and what I discovered is that
their implementation doesn't have any chunk headers: chunks of
the same size are allocated consecutively within pages, and all
the bookkeeping data is somewhere else.  Presumably FreeBSD is
the same.  So the apparent special case with 0010 is an illusion,
even though I saw it on two different machines (maybe it's a
specific value that we're allocating??)  The most likely case
is 0000 due to the immediately previous word having never been
used (note that like palloc, they round chunk sizes up to powers
of two, so unused space at the end of a chunk is common).  I'm
not sure whether the cases I saw with 1111 are chance artifacts
or reflect some real mechanism, but probably the former.  I
thought for a bit that that might be the effects of wipe_mem
on the previous chunk, but palloc'd storage would never share
the same page as malloc'd storage under this allocator, because
we grab it from malloc in larger-than-page chunks.

However ... after looking into glib's malloc.c, I find that
it does use a chunk header, and very conveniently the three bits
that we care about are flag bits (at least on 64-bit machines):

    chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
	    |             Size of previous chunk, if unallocated (P clear)  |
	    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
	    |             Size of chunk, in bytes                     |A|M|P|
      mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
	    |             User data starts here...                          .

The A bit is only used when threading, and hence should always
be zero in our usage.  The M bit only gets set in chunks large
enough to be separately mmap'd, so when it is set P must be 0.
If M is not set then P seems to usually be 1, although it could
be 0.  So the three possibilities for what we can see under
glibc are 000, 001, 010 (the last only occuring for chunks
larger than 128K).  This squares with experimental results on
my machine --- I'd not thought to try sizes above 100K before.

So I'm still inclined to leave 001 and 010 both unused, but the
reason why is different than I thought before.

Going forward, we could commandeer 010 if we need to without losing
very much debuggability, since malloc'ing more than 128K in a chunk
won't happen often.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-06 23:35  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-10-06 23:35 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

I wrote:
> So I'm still inclined to leave 001 and 010 both unused, but the
> reason why is different than I thought before.

Which leaves me with the attached proposed wording.

			regards, tom lane

Attachments:

more-mcxt-robustness-3.patch (text/x-diff, 7.2K) download diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index c80236d285..b1a3c74830 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -32,6 +32,11 @@ #include "utils/memutils_internal.h" +static void BogusFree(void *pointer); +static void *BogusRealloc(void *pointer, Size size); +static MemoryContext BogusGetChunkContext(void *pointer); +static Size BogusGetChunkSpace(void *pointer); + /***************************************************************************** * GLOBAL MEMORY * *****************************************************************************/ @@ -74,10 +79,42 @@ static const MemoryContextMethods mcxt_methods[] = { [MCTX_SLAB_ID].get_chunk_context = SlabGetChunkContext, [MCTX_SLAB_ID].get_chunk_space = SlabGetChunkSpace, [MCTX_SLAB_ID].is_empty = SlabIsEmpty, - [MCTX_SLAB_ID].stats = SlabStats + [MCTX_SLAB_ID].stats = SlabStats, #ifdef MEMORY_CONTEXT_CHECKING - ,[MCTX_SLAB_ID].check = SlabCheck + [MCTX_SLAB_ID].check = SlabCheck, #endif + + /* + * Unused (as yet) IDs should have dummy entries here. This allows us to + * fail cleanly if a bogus pointer is passed to pfree or the like. It + * seems sufficient to provide routines for the methods that might get + * invoked from inspection of a chunk (see MCXT_METHOD calls below). + */ + + [MCTX_UNUSED1_ID].free_p = BogusFree, + [MCTX_UNUSED1_ID].realloc = BogusRealloc, + [MCTX_UNUSED1_ID].get_chunk_context = BogusGetChunkContext, + [MCTX_UNUSED1_ID].get_chunk_space = BogusGetChunkSpace, + + [MCTX_UNUSED2_ID].free_p = BogusFree, + [MCTX_UNUSED2_ID].realloc = BogusRealloc, + [MCTX_UNUSED2_ID].get_chunk_context = BogusGetChunkContext, + [MCTX_UNUSED2_ID].get_chunk_space = BogusGetChunkSpace, + + [MCTX_UNUSED3_ID].free_p = BogusFree, + [MCTX_UNUSED3_ID].realloc = BogusRealloc, + [MCTX_UNUSED3_ID].get_chunk_context = BogusGetChunkContext, + [MCTX_UNUSED3_ID].get_chunk_space = BogusGetChunkSpace, + + [MCTX_UNUSED4_ID].free_p = BogusFree, + [MCTX_UNUSED4_ID].realloc = BogusRealloc, + [MCTX_UNUSED4_ID].get_chunk_context = BogusGetChunkContext, + [MCTX_UNUSED4_ID].get_chunk_space = BogusGetChunkSpace, + + [MCTX_UNUSED5_ID].free_p = BogusFree, + [MCTX_UNUSED5_ID].realloc = BogusRealloc, + [MCTX_UNUSED5_ID].get_chunk_context = BogusGetChunkContext, + [MCTX_UNUSED5_ID].get_chunk_space = BogusGetChunkSpace, }; /* @@ -125,6 +162,77 @@ static void MemoryContextStatsPrint(MemoryContext context, void *passthru, #define MCXT_METHOD(pointer, method) \ mcxt_methods[GetMemoryChunkMethodID(pointer)].method +/* + * GetMemoryChunkMethodID + * Return the MemoryContextMethodID from the uint64 chunk header which + * directly precedes 'pointer'. + */ +static inline MemoryContextMethodID +GetMemoryChunkMethodID(const void *pointer) +{ + uint64 header; + + /* + * Try to detect bogus pointers handed to us, poorly though we can. + * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an + * allocated chunk. + */ + Assert(pointer == (const void *) MAXALIGN(pointer)); + + header = *((const uint64 *) ((const char *) pointer - sizeof(uint64))); + + return (MemoryContextMethodID) (header & MEMORY_CONTEXT_METHODID_MASK); +} + +/* + * GetMemoryChunkHeader + * Return the uint64 chunk header which directly precedes 'pointer'. + * + * This is only used after GetMemoryChunkMethodID, so no need for error checks. + */ +static inline uint64 +GetMemoryChunkHeader(const void *pointer) +{ + return *((const uint64 *) ((const char *) pointer - sizeof(uint64))); +} + +/* + * Support routines to trap use of invalid memory context method IDs + * (from calling pfree or the like on a bogus pointer). As a possible + * aid in debugging, we report the header word along with the pointer + * address (if we got here, there must be an accessible header word). + */ +static void +BogusFree(void *pointer) +{ + elog(ERROR, "pfree called with invalid pointer %p (header 0x%016llx)", + pointer, (long long) GetMemoryChunkHeader(pointer)); +} + +static void * +BogusRealloc(void *pointer, Size size) +{ + elog(ERROR, "repalloc called with invalid pointer %p (header 0x%016llx)", + pointer, (long long) GetMemoryChunkHeader(pointer)); + return NULL; /* keep compiler quiet */ +} + +static MemoryContext +BogusGetChunkContext(void *pointer) +{ + elog(ERROR, "GetMemoryChunkContext called with invalid pointer %p (header 0x%016llx)", + pointer, (long long) GetMemoryChunkHeader(pointer)); + return NULL; /* keep compiler quiet */ +} + +static Size +BogusGetChunkSpace(void *pointer) +{ + elog(ERROR, "GetMemoryChunkSpace called with invalid pointer %p (header 0x%016llx)", + pointer, (long long) GetMemoryChunkHeader(pointer)); + return 0; /* keep compiler quiet */ +} + /***************************************************************************** * EXPORTED ROUTINES * diff --git a/src/include/utils/memutils_internal.h b/src/include/utils/memutils_internal.h index 377cee7a84..bc2cbdd506 100644 --- a/src/include/utils/memutils_internal.h +++ b/src/include/utils/memutils_internal.h @@ -74,15 +74,26 @@ extern void SlabCheck(MemoryContext context); * MemoryContextMethodID * A unique identifier for each MemoryContext implementation which * indicates the index into the mcxt_methods[] array. See mcxt.c. - * The maximum value for this enum is constrained by - * MEMORY_CONTEXT_METHODID_MASK. If an enum value higher than that is - * required then MEMORY_CONTEXT_METHODID_BITS will need to be increased. + * + * For robust error detection, ensure that MemoryContextMethodID has a value + * for each possible bit-pattern of MEMORY_CONTEXT_METHODID_MASK, and make + * dummy entries for unused IDs in the mcxt_methods[] array. We also try + * to avoid using bit-patterns as valid IDs if they are likely to occur in + * garbage data, or if they could falsely match on chunks that are really from + * malloc not palloc. (We can't tell that for most malloc implementations, + * but it happens that glibc stores flag bits in the same place where we put + * the MemoryContextMethodID, so the possible values are predictable for it.) */ typedef enum MemoryContextMethodID { + MCTX_UNUSED1_ID, /* 000 occurs in never-used memory */ + MCTX_UNUSED2_ID, /* glibc malloc'd chunks usually match 001 */ + MCTX_UNUSED3_ID, /* glibc malloc'd chunks > 128kB match 010 */ MCTX_ASET_ID, MCTX_GENERATION_ID, MCTX_SLAB_ID, + MCTX_UNUSED4_ID, /* available */ + MCTX_UNUSED5_ID /* 111 occurs in wipe_mem'd memory */ } MemoryContextMethodID; /* @@ -104,27 +115,4 @@ extern void MemoryContextCreate(MemoryContext node, MemoryContext parent, const char *name); -/* - * GetMemoryChunkMethodID - * Return the MemoryContextMethodID from the uint64 chunk header which - * directly precedes 'pointer'. - */ -static inline MemoryContextMethodID -GetMemoryChunkMethodID(void *pointer) -{ - uint64 header; - - /* - * Try to detect bogus pointers handed to us, poorly though we can. - * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an - * allocated chunk. - */ - Assert(pointer != NULL); - Assert(pointer == (void *) MAXALIGN(pointer)); - - header = *((uint64 *) ((char *) pointer - sizeof(uint64))); - - return (MemoryContextMethodID) (header & MEMORY_CONTEXT_METHODID_MASK); -} - #endif /* MEMUTILS_INTERNAL_H */
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-07 00:50  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-10-07 00:50 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Fri, 7 Oct 2022 at 12:35, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Which leaves me with the attached proposed wording.

No objections here.

With these comments I'd be using slot MCTX_UNUSED4_ID first, then I'd
probably be looking at MCTX_UNUSED5_ID after adjusting wipe_mem to do
something other than setting bytes to 0x7F. I'd then use
MCTX_UNUSED3_ID since that pattern is only used for larger chunks with
glibc (per your findings).  After that, I'd probably start looking
into making more than 3 bits available. If that wasn't possible, I'd
be using MCTX_UNUSED2_ID and at last resort MCTX_UNUSED1_ID.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-07 01:00  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-10-07 01:00 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> On Fri, 7 Oct 2022 at 12:35, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> Which leaves me with the attached proposed wording.

> No objections here.

Cool, I'll push in a little bit.

> With these comments I'd be using slot MCTX_UNUSED4_ID first, then I'd
> probably be looking at MCTX_UNUSED5_ID after adjusting wipe_mem to do
> something other than setting bytes to 0x7F.

Well, the only way that you could free up a bitpattern that way is
to make wipe_mem use something ending in 000 or 001.  I'd be against
using 000 because then wiped memory might appear to contain valid
(aligned) pointers.  But perhaps 001 would be ok.

> I'd then use
> MCTX_UNUSED3_ID since that pattern is only used for larger chunks with
> glibc (per your findings).  After that, I'd probably start looking
> into making more than 3 bits available. If that wasn't possible, I'd
> be using MCTX_UNUSED2_ID and at last resort MCTX_UNUSED1_ID.

If we get to having three-quarters or seven-eighths of the bitpatterns
being valid IDs, we'll have precious little ability to detect garbage.
So personally I'd put "find a fourth bit" higher on the priority list.

In any case, we needn't invest more effort here until someone comes
with a fifth context method ... and I don't recall hearing discussions
of even a fourth one yet.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-08 15:52  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-10-08 15:52 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

So I pushed that, but I don't feel that we're out of the woods yet.
As I mentioned at [1], while testing this stuff I hit a case where
aset.c will try to wipe_mem practically the entire address space after
being asked to pfree() an invalid pointer.  The specific reproducer
isn't too interesting because it depends on the pre-80ef92675 state of
the code, but what I take away from this is that aset.c is still far
too fragile as it stands.

One problem is that aset.c generally isn't too careful about whether
a putative chunk is actually one of its chunks.  That was okay before
c6e0fe1f2 because we would never get to AllocSetFree etc unless the
word before the chunk data pointed at a moderately-sane AllocSet.
Now, we can arrive at that code on the strength of three random bits,
so it's got to be more careful.  In the attached patch, I make
AllocSetIsValid do an IsA() test, and make sure to apply it to the
aset we think we have found from the chunk header.  This is not in
any way a new check: what it is doing is replacing the IsA check done
by the "AssertArg(MemoryContextIsValid(context))" that was performed
by GetMemoryChunkContext in the old code, and that we've completely
lost in the code as it stands.

The other problem, which is what is leading to wipe_mem-the-universe,
is that aset.c figures the size of a non-external chunk essentially
as "1 << MemoryChunkGetValue(chunk)", where the "value" field is 30
bits wide and has undergone exactly zero validation before
AllocSetFree uses the size in memset.  That's far, far too trusting.
In the attached I put in some asserts to verify that the value field
is in the valid range for a freelist index, which should usually
trigger if we have a garbage value, or at the very least constrain
the damage.

What I am mainly wondering about at this point is whether Asserts
are good enough or we should use actual test-and-elog checks for
these things.  The precedent of the old GetMemoryChunkContext
implementation suggests that assertions are good enough for the
AllocSetIsValid tests.  On the other hand, there are existing
cross-checks like

        if (block->freeptr != block->endptr)
            elog(ERROR, "could not find block containing chunk %p", chunk);

so at least in some code paths we've thought it is worth expending
such tests in production builds.  Any opinions?

I imagine generation.c and slab.c need similar bulletproofing
measures, but I didn't look at them yet.

			regards, tom lane

[1] https://www.postgresql.org/message-id/3436789.1665187055%40sss.pgh.pa.us

Attachments:

harden-aset-some-more-1.patch (text/x-diff, 6.8K) download diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index ec423375ae..76a9f02bd8 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -132,6 +132,10 @@ typedef struct AllocFreeListLink #define GetFreeListLink(chkptr) \ (AllocFreeListLink *) ((char *) (chkptr) + ALLOC_CHUNKHDRSZ) +/* Validate a freelist index retrieved from a chunk header */ +#define FreeListIdxIsValid(fidx) \ + ((fidx) >= 0 && (fidx) < ALLOCSET_NUM_FREELISTS) + /* Determine the size of the chunk based on the freelist index */ #define GetChunkSizeFromFreeListIdx(fidx) \ ((((Size) 1) << ALLOC_MINBITS) << (fidx)) @@ -202,7 +206,15 @@ typedef struct AllocBlockData * AllocSetIsValid * True iff set is valid allocation set. */ -#define AllocSetIsValid(set) PointerIsValid(set) +#define AllocSetIsValid(set) \ + (PointerIsValid(set) && IsA(set, AllocSetContext)) + +/* + * AllocBlockIsValid + * True iff block is valid block of allocation set. + */ +#define AllocBlockIsValid(block) \ + (PointerIsValid(block) && AllocSetIsValid((block)->aset)) /* * We always store external chunks on a dedicated block. This makes fetching @@ -530,8 +542,7 @@ AllocSetReset(MemoryContext context) { AllocSet set = (AllocSet) context; AllocBlock block; - Size keepersize PG_USED_FOR_ASSERTS_ONLY - = set->keeper->endptr - ((char *) set); + Size keepersize PG_USED_FOR_ASSERTS_ONLY; AssertArg(AllocSetIsValid(set)); @@ -540,6 +551,9 @@ AllocSetReset(MemoryContext context) AllocSetCheck(context); #endif + /* Remember keeper block size for Assert below */ + keepersize = set->keeper->endptr - ((char *) set); + /* Clear chunk freelists */ MemSetAligned(set->freelist, 0, sizeof(set->freelist)); @@ -598,8 +612,7 @@ AllocSetDelete(MemoryContext context) { AllocSet set = (AllocSet) context; AllocBlock block = set->blocks; - Size keepersize PG_USED_FOR_ASSERTS_ONLY - = set->keeper->endptr - ((char *) set); + Size keepersize PG_USED_FOR_ASSERTS_ONLY; AssertArg(AllocSetIsValid(set)); @@ -608,6 +621,9 @@ AllocSetDelete(MemoryContext context) AllocSetCheck(context); #endif + /* Remember keeper block size for Assert below */ + keepersize = set->keeper->endptr - ((char *) set); + /* * If the context is a candidate for a freelist, put it into that freelist * instead of destroying it. @@ -994,9 +1010,10 @@ AllocSetFree(void *pointer) if (MemoryChunkIsExternal(chunk)) { - + /* Release single-chunk block. */ AllocBlock block = ExternalChunkGetBlock(chunk); + AssertArg(AllocBlockIsValid(block)); set = block->aset; #ifdef MEMORY_CONTEXT_CHECKING @@ -1011,7 +1028,6 @@ AllocSetFree(void *pointer) } #endif - /* * Try to verify that we have a sane block pointer, the freeptr should * match the endptr. @@ -1036,12 +1052,17 @@ AllocSetFree(void *pointer) } else { - int fidx = MemoryChunkGetValue(chunk); AllocBlock block = MemoryChunkGetBlock(chunk); - AllocFreeListLink *link = GetFreeListLink(chunk); + int fidx; + AllocFreeListLink *link; + AssertArg(AllocBlockIsValid(block)); set = block->aset; + fidx = MemoryChunkGetValue(chunk); + Assert(FreeListIdxIsValid(fidx)); + link = GetFreeListLink(chunk); + #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ if (chunk->requested_size < GetChunkSizeFromFreeListIdx(fidx)) @@ -1089,6 +1110,7 @@ AllocSetRealloc(void *pointer, Size size) AllocSet set; MemoryChunk *chunk = PointerGetMemoryChunk(pointer); Size oldsize; + int fidx; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); @@ -1105,9 +1127,11 @@ AllocSetRealloc(void *pointer, Size size) Size oldblksize; block = ExternalChunkGetBlock(chunk); - oldsize = block->endptr - (char *) pointer; + AssertArg(AllocBlockIsValid(block)); set = block->aset; + oldsize = block->endptr - (char *) pointer; + #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ Assert(chunk->requested_size < oldsize); @@ -1201,9 +1225,13 @@ AllocSetRealloc(void *pointer, Size size) } block = MemoryChunkGetBlock(chunk); - oldsize = GetChunkSizeFromFreeListIdx(MemoryChunkGetValue(chunk)); + AssertArg(AllocBlockIsValid(block)); set = block->aset; + fidx = MemoryChunkGetValue(chunk); + Assert(FreeListIdxIsValid(fidx)); + oldsize = GetChunkSizeFromFreeListIdx(fidx); + #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ if (chunk->requested_size < oldsize) @@ -1328,6 +1356,7 @@ AllocSetGetChunkContext(void *pointer) else block = (AllocBlock) MemoryChunkGetBlock(chunk); + AssertArg(AllocBlockIsValid(block)); set = block->aset; return &set->header; @@ -1342,16 +1371,19 @@ Size AllocSetGetChunkSpace(void *pointer) { MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + int fidx; if (MemoryChunkIsExternal(chunk)) { AllocBlock block = ExternalChunkGetBlock(chunk); + AssertArg(AllocBlockIsValid(block)); return block->endptr - (char *) chunk; } - return GetChunkSizeFromFreeListIdx(MemoryChunkGetValue(chunk)) + - ALLOC_CHUNKHDRSZ; + fidx = MemoryChunkGetValue(chunk); + Assert(FreeListIdxIsValid(fidx)); + return GetChunkSizeFromFreeListIdx(fidx) + ALLOC_CHUNKHDRSZ; } /* @@ -1361,6 +1393,8 @@ AllocSetGetChunkSpace(void *pointer) bool AllocSetIsEmpty(MemoryContext context) { + AssertArg(AllocSetIsValid(context)); + /* * For now, we say "empty" only if the context is new or just reset. We * could examine the freelists to determine if all space has been freed, @@ -1394,6 +1428,8 @@ AllocSetStats(MemoryContext context, AllocBlock block; int fidx; + AssertArg(AllocSetIsValid(set)); + /* Include context header in totalspace */ totalspace = MAXALIGN(sizeof(AllocSetContext)); @@ -1405,14 +1441,14 @@ AllocSetStats(MemoryContext context, } for (fidx = 0; fidx < ALLOCSET_NUM_FREELISTS; fidx++) { + Size chksz = GetChunkSizeFromFreeListIdx(fidx); MemoryChunk *chunk = set->freelist[fidx]; while (chunk != NULL) { - Size chksz = GetChunkSizeFromFreeListIdx(MemoryChunkGetValue(chunk)); AllocFreeListLink *link = GetFreeListLink(chunk); - Assert(GetChunkSizeFromFreeListIdx(fidx) == chksz); + Assert(MemoryChunkGetValue(chunk) == fidx); freechunks++; freespace += chksz + ALLOC_CHUNKHDRSZ; @@ -1522,7 +1558,13 @@ AllocSetCheck(MemoryContext context) } else { - chsize = GetChunkSizeFromFreeListIdx(MemoryChunkGetValue(chunk)); /* aligned chunk size */ + int fidx = MemoryChunkGetValue(chunk); + + if (!FreeListIdxIsValid(fidx)) + elog(WARNING, "problem in alloc set %s: bad chunk size for chunk %p in block %p", + name, chunk, block); + + chsize = GetChunkSizeFromFreeListIdx(fidx); /* aligned chunk size */ /* * Check the stored block offset correctly references this
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-10 19:35  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-10-10 19:35 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

I wrote:
> What I am mainly wondering about at this point is whether Asserts
> are good enough or we should use actual test-and-elog checks for
> these things.

Hearing no comments on that, I decided that a good policy would be
to use Asserts in the paths dealing with small chunks but test-and-elog
in the paths dealing with large chunks.  We already had test-and-elog
sanity checks in the latter paths, at least in aset.c, which the new
checks can reasonably be combined with.  It's unlikely that the
large-chunk case is at all performance-critical, too.  But adding
runtime checks in the small-chunk paths would probably risk losing
some performance in production builds, and I'm not currently prepared
to argue that the problem is big enough to justify that.

Hence v2 attached, which cleans things up a tad in aset.c and then
extends similar policy to generation.c and slab.c.  Of note is
that slab.c was doing things like this:

	SlabContext *slab = castNode(SlabContext, context);

	Assert(slab);

which has about the same effect as what I'm proposing with
AllocSetIsValid, but (a) it's randomly different from the
other allocators, and (b) it's probably a hair less efficient,
because I doubt the compiler can optimize away castNode's
special handling of NULL.  So I made these bits follow the
style of aset.c.

			regards, tom lane

Attachments:

harden-allocators-some-more-2.patch (text/x-diff, 16.8K) download diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index ec423375ae..db402e3a41 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -132,6 +132,10 @@ typedef struct AllocFreeListLink #define GetFreeListLink(chkptr) \ (AllocFreeListLink *) ((char *) (chkptr) + ALLOC_CHUNKHDRSZ) +/* Validate a freelist index retrieved from a chunk header */ +#define FreeListIdxIsValid(fidx) \ + ((fidx) >= 0 && (fidx) < ALLOCSET_NUM_FREELISTS) + /* Determine the size of the chunk based on the freelist index */ #define GetChunkSizeFromFreeListIdx(fidx) \ ((((Size) 1) << ALLOC_MINBITS) << (fidx)) @@ -202,7 +206,15 @@ typedef struct AllocBlockData * AllocSetIsValid * True iff set is valid allocation set. */ -#define AllocSetIsValid(set) PointerIsValid(set) +#define AllocSetIsValid(set) \ + (PointerIsValid(set) && IsA(set, AllocSetContext)) + +/* + * AllocBlockIsValid + * True iff block is valid block of allocation set. + */ +#define AllocBlockIsValid(block) \ + (PointerIsValid(block) && AllocSetIsValid((block)->aset)) /* * We always store external chunks on a dedicated block. This makes fetching @@ -530,8 +542,7 @@ AllocSetReset(MemoryContext context) { AllocSet set = (AllocSet) context; AllocBlock block; - Size keepersize PG_USED_FOR_ASSERTS_ONLY - = set->keeper->endptr - ((char *) set); + Size keepersize PG_USED_FOR_ASSERTS_ONLY; AssertArg(AllocSetIsValid(set)); @@ -540,6 +551,9 @@ AllocSetReset(MemoryContext context) AllocSetCheck(context); #endif + /* Remember keeper block size for Assert below */ + keepersize = set->keeper->endptr - ((char *) set); + /* Clear chunk freelists */ MemSetAligned(set->freelist, 0, sizeof(set->freelist)); @@ -598,8 +612,7 @@ AllocSetDelete(MemoryContext context) { AllocSet set = (AllocSet) context; AllocBlock block = set->blocks; - Size keepersize PG_USED_FOR_ASSERTS_ONLY - = set->keeper->endptr - ((char *) set); + Size keepersize PG_USED_FOR_ASSERTS_ONLY; AssertArg(AllocSetIsValid(set)); @@ -608,6 +621,9 @@ AllocSetDelete(MemoryContext context) AllocSetCheck(context); #endif + /* Remember keeper block size for Assert below */ + keepersize = set->keeper->endptr - ((char *) set); + /* * If the context is a candidate for a freelist, put it into that freelist * instead of destroying it. @@ -994,9 +1010,16 @@ AllocSetFree(void *pointer) if (MemoryChunkIsExternal(chunk)) { - + /* Release single-chunk block. */ AllocBlock block = ExternalChunkGetBlock(chunk); + /* + * Try to verify that we have a sane block pointer: the block header + * should reference an aset and the freeptr should match the endptr. + */ + if (!AllocBlockIsValid(block) || block->freeptr != block->endptr) + elog(ERROR, "could not find block containing chunk %p", chunk); + set = block->aset; #ifdef MEMORY_CONTEXT_CHECKING @@ -1011,14 +1034,6 @@ AllocSetFree(void *pointer) } #endif - - /* - * Try to verify that we have a sane block pointer, the freeptr should - * match the endptr. - */ - if (block->freeptr != block->endptr) - elog(ERROR, "could not find block containing chunk %p", chunk); - /* OK, remove block from aset's list and free it */ if (block->prev) block->prev->next = block->next; @@ -1036,12 +1051,23 @@ AllocSetFree(void *pointer) } else { - int fidx = MemoryChunkGetValue(chunk); AllocBlock block = MemoryChunkGetBlock(chunk); - AllocFreeListLink *link = GetFreeListLink(chunk); + int fidx; + AllocFreeListLink *link; + /* + * In this path, for speed reasons we just Assert that the referenced + * block is good. We can also Assert that the value field is sane. + * Future field experience may show that these Asserts had better + * become regular runtime test-and-elog checks. + */ + AssertArg(AllocBlockIsValid(block)); set = block->aset; + fidx = MemoryChunkGetValue(chunk); + Assert(FreeListIdxIsValid(fidx)); + link = GetFreeListLink(chunk); + #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ if (chunk->requested_size < GetChunkSizeFromFreeListIdx(fidx)) @@ -1089,6 +1115,7 @@ AllocSetRealloc(void *pointer, Size size) AllocSet set; MemoryChunk *chunk = PointerGetMemoryChunk(pointer); Size oldsize; + int fidx; /* Allow access to private part of chunk header. */ VALGRIND_MAKE_MEM_DEFINED(chunk, ALLOCCHUNK_PRIVATE_LEN); @@ -1105,9 +1132,18 @@ AllocSetRealloc(void *pointer, Size size) Size oldblksize; block = ExternalChunkGetBlock(chunk); - oldsize = block->endptr - (char *) pointer; + + /* + * Try to verify that we have a sane block pointer: the block header + * should reference an aset and the freeptr should match the endptr. + */ + if (!AllocBlockIsValid(block) || block->freeptr != block->endptr) + elog(ERROR, "could not find block containing chunk %p", chunk); + set = block->aset; + oldsize = block->endptr - (char *) pointer; + #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ Assert(chunk->requested_size < oldsize); @@ -1116,13 +1152,6 @@ AllocSetRealloc(void *pointer, Size size) set->header.name, chunk); #endif - /* - * Try to verify that we have a sane block pointer, the freeptr should - * match the endptr. - */ - if (block->freeptr != block->endptr) - elog(ERROR, "could not find block containing chunk %p", chunk); - #ifdef MEMORY_CONTEXT_CHECKING /* ensure there's always space for the sentinel byte */ chksize = MAXALIGN(size + 1); @@ -1201,9 +1230,20 @@ AllocSetRealloc(void *pointer, Size size) } block = MemoryChunkGetBlock(chunk); - oldsize = GetChunkSizeFromFreeListIdx(MemoryChunkGetValue(chunk)); + + /* + * In this path, for speed reasons we just Assert that the referenced + * block is good. We can also Assert that the value field is sane. Future + * field experience may show that these Asserts had better become regular + * runtime test-and-elog checks. + */ + AssertArg(AllocBlockIsValid(block)); set = block->aset; + fidx = MemoryChunkGetValue(chunk); + Assert(FreeListIdxIsValid(fidx)); + oldsize = GetChunkSizeFromFreeListIdx(fidx); + #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ if (chunk->requested_size < oldsize) @@ -1328,6 +1368,7 @@ AllocSetGetChunkContext(void *pointer) else block = (AllocBlock) MemoryChunkGetBlock(chunk); + AssertArg(AllocBlockIsValid(block)); set = block->aset; return &set->header; @@ -1342,16 +1383,19 @@ Size AllocSetGetChunkSpace(void *pointer) { MemoryChunk *chunk = PointerGetMemoryChunk(pointer); + int fidx; if (MemoryChunkIsExternal(chunk)) { AllocBlock block = ExternalChunkGetBlock(chunk); + AssertArg(AllocBlockIsValid(block)); return block->endptr - (char *) chunk; } - return GetChunkSizeFromFreeListIdx(MemoryChunkGetValue(chunk)) + - ALLOC_CHUNKHDRSZ; + fidx = MemoryChunkGetValue(chunk); + Assert(FreeListIdxIsValid(fidx)); + return GetChunkSizeFromFreeListIdx(fidx) + ALLOC_CHUNKHDRSZ; } /* @@ -1361,6 +1405,8 @@ AllocSetGetChunkSpace(void *pointer) bool AllocSetIsEmpty(MemoryContext context) { + AssertArg(AllocSetIsValid(context)); + /* * For now, we say "empty" only if the context is new or just reset. We * could examine the freelists to determine if all space has been freed, @@ -1394,6 +1440,8 @@ AllocSetStats(MemoryContext context, AllocBlock block; int fidx; + AssertArg(AllocSetIsValid(set)); + /* Include context header in totalspace */ totalspace = MAXALIGN(sizeof(AllocSetContext)); @@ -1405,14 +1453,14 @@ AllocSetStats(MemoryContext context, } for (fidx = 0; fidx < ALLOCSET_NUM_FREELISTS; fidx++) { + Size chksz = GetChunkSizeFromFreeListIdx(fidx); MemoryChunk *chunk = set->freelist[fidx]; while (chunk != NULL) { - Size chksz = GetChunkSizeFromFreeListIdx(MemoryChunkGetValue(chunk)); AllocFreeListLink *link = GetFreeListLink(chunk); - Assert(GetChunkSizeFromFreeListIdx(fidx) == chksz); + Assert(MemoryChunkGetValue(chunk) == fidx); freechunks++; freespace += chksz + ALLOC_CHUNKHDRSZ; @@ -1522,7 +1570,13 @@ AllocSetCheck(MemoryContext context) } else { - chsize = GetChunkSizeFromFreeListIdx(MemoryChunkGetValue(chunk)); /* aligned chunk size */ + int fidx = MemoryChunkGetValue(chunk); + + if (!FreeListIdxIsValid(fidx)) + elog(WARNING, "problem in alloc set %s: bad chunk size for chunk %p in block %p", + name, chunk, block); + + chsize = GetChunkSizeFromFreeListIdx(fidx); /* aligned chunk size */ /* * Check the stored block offset correctly references this diff --git a/src/backend/utils/mmgr/generation.c b/src/backend/utils/mmgr/generation.c index c743b24fa7..4cb75f493f 100644 --- a/src/backend/utils/mmgr/generation.c +++ b/src/backend/utils/mmgr/generation.c @@ -105,11 +105,20 @@ struct GenerationBlock * simplicity. */ #define GENERATIONCHUNK_PRIVATE_LEN offsetof(MemoryChunk, hdrmask) + /* * GenerationIsValid - * True iff set is valid allocation set. + * True iff set is valid generation set. + */ +#define GenerationIsValid(set) \ + (PointerIsValid(set) && IsA(set, GenerationContext)) + +/* + * GenerationBlockIsValid + * True iff block is valid block of generation set. */ -#define GenerationIsValid(set) PointerIsValid(set) +#define GenerationBlockIsValid(block) \ + (PointerIsValid(block) && GenerationIsValid((block)->context)) /* * We always store external chunks on a dedicated block. This makes fetching @@ -345,6 +354,8 @@ GenerationAlloc(MemoryContext context, Size size) Size chunk_size; Size required_size; + AssertArg(GenerationIsValid(set)); + #ifdef MEMORY_CONTEXT_CHECKING /* ensure there's always space for the sentinel byte */ chunk_size = MAXALIGN(size + 1); @@ -625,6 +636,14 @@ GenerationFree(void *pointer) if (MemoryChunkIsExternal(chunk)) { block = ExternalChunkGetBlock(chunk); + + /* + * Try to verify that we have a sane block pointer: the block header + * should reference a generation context. + */ + if (!GenerationBlockIsValid(block)) + elog(ERROR, "could not find block containing chunk %p", chunk); + #if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) chunksize = block->endptr - (char *) pointer; #endif @@ -632,6 +651,14 @@ GenerationFree(void *pointer) else { block = MemoryChunkGetBlock(chunk); + + /* + * In this path, for speed reasons we just Assert that the referenced + * block is good. Future field experience may show that this Assert + * had better become a regular runtime test-and-elog check. + */ + AssertArg(GenerationBlockIsValid(block)); + #if defined(MEMORY_CONTEXT_CHECKING) || defined(CLOBBER_FREED_MEMORY) chunksize = MemoryChunkGetValue(chunk); #endif @@ -723,11 +750,27 @@ GenerationRealloc(void *pointer, Size size) if (MemoryChunkIsExternal(chunk)) { block = ExternalChunkGetBlock(chunk); + + /* + * Try to verify that we have a sane block pointer: the block header + * should reference a generation context. + */ + if (!GenerationBlockIsValid(block)) + elog(ERROR, "could not find block containing chunk %p", chunk); + oldsize = block->endptr - (char *) pointer; } else { block = MemoryChunkGetBlock(chunk); + + /* + * In this path, for speed reasons we just Assert that the referenced + * block is good. Future field experience may show that this Assert + * had better become a regular runtime test-and-elog check. + */ + AssertArg(GenerationBlockIsValid(block)); + oldsize = MemoryChunkGetValue(chunk); } @@ -845,6 +888,7 @@ GenerationGetChunkContext(void *pointer) else block = (GenerationBlock *) MemoryChunkGetBlock(chunk); + AssertArg(GenerationBlockIsValid(block)); return &block->context->header; } @@ -863,6 +907,7 @@ GenerationGetChunkSpace(void *pointer) { GenerationBlock *block = ExternalChunkGetBlock(chunk); + AssertArg(GenerationBlockIsValid(block)); chunksize = block->endptr - (char *) pointer; } else @@ -881,6 +926,8 @@ GenerationIsEmpty(MemoryContext context) GenerationContext *set = (GenerationContext *) context; dlist_iter iter; + AssertArg(GenerationIsValid(set)); + dlist_foreach(iter, &set->blocks) { GenerationBlock *block = dlist_container(GenerationBlock, node, iter.cur); @@ -917,6 +964,8 @@ GenerationStats(MemoryContext context, Size freespace = 0; dlist_iter iter; + AssertArg(GenerationIsValid(set)); + /* Include context header in totalspace */ totalspace = MAXALIGN(sizeof(GenerationContext)); diff --git a/src/backend/utils/mmgr/slab.c b/src/backend/utils/mmgr/slab.c index 9149aaafcb..f4f40007a4 100644 --- a/src/backend/utils/mmgr/slab.c +++ b/src/backend/utils/mmgr/slab.c @@ -111,6 +111,21 @@ typedef struct SlabBlock #define SlabChunkIndex(slab, block, chunk) \ (((char *) chunk - SlabBlockStart(block)) / slab->fullChunkSize) +/* + * SlabIsValid + * True iff set is valid slab allocation set. + */ +#define SlabIsValid(set) \ + (PointerIsValid(set) && IsA(set, SlabContext)) + +/* + * SlabBlockIsValid + * True iff block is valid block of slab allocation set. + */ +#define SlabBlockIsValid(block) \ + (PointerIsValid(block) && SlabIsValid((block)->slab)) + + /* * SlabContextCreate * Create a new Slab context. @@ -236,10 +251,10 @@ SlabContextCreate(MemoryContext parent, void SlabReset(MemoryContext context) { + SlabContext *slab = (SlabContext *) context; int i; - SlabContext *slab = castNode(SlabContext, context); - Assert(slab); + AssertArg(SlabIsValid(slab)); #ifdef MEMORY_CONTEXT_CHECKING /* Check for corruption and leaks before freeing */ @@ -293,12 +308,12 @@ SlabDelete(MemoryContext context) void * SlabAlloc(MemoryContext context, Size size) { - SlabContext *slab = castNode(SlabContext, context); + SlabContext *slab = (SlabContext *) context; SlabBlock *block; MemoryChunk *chunk; int idx; - Assert(slab); + AssertArg(SlabIsValid(slab)); Assert((slab->minFreeChunks >= 0) && (slab->minFreeChunks < slab->chunksPerBlock)); @@ -450,10 +465,18 @@ SlabAlloc(MemoryContext context, Size size) void SlabFree(void *pointer) { - int idx; MemoryChunk *chunk = PointerGetMemoryChunk(pointer); SlabBlock *block = MemoryChunkGetBlock(chunk); - SlabContext *slab = block->slab; + SlabContext *slab; + int idx; + + /* + * Try to verify that we have a sane block pointer: the block header + * should reference a slab context. + */ + if (!SlabBlockIsValid(block)) + elog(ERROR, "could not find block containing chunk %p", chunk); + slab = block->slab; #ifdef MEMORY_CONTEXT_CHECKING /* Test for someone scribbling on unused space in chunk */ @@ -540,9 +563,16 @@ SlabRealloc(void *pointer, Size size) { MemoryChunk *chunk = PointerGetMemoryChunk(pointer); SlabBlock *block = MemoryChunkGetBlock(chunk); - SlabContext *slab = block->slab; + SlabContext *slab; + + /* + * Try to verify that we have a sane block pointer: the block header + * should reference a slab context. + */ + if (!SlabBlockIsValid(block)) + elog(ERROR, "could not find block containing chunk %p", chunk); + slab = block->slab; - Assert(slab); /* can't do actual realloc with slab, but let's try to be gentle */ if (size == slab->chunkSize) return pointer; @@ -560,11 +590,9 @@ SlabGetChunkContext(void *pointer) { MemoryChunk *chunk = PointerGetMemoryChunk(pointer); SlabBlock *block = MemoryChunkGetBlock(chunk); - SlabContext *slab = block->slab; - - Assert(slab != NULL); - return &slab->header; + AssertArg(SlabBlockIsValid(block)); + return &block->slab->header; } /* @@ -577,9 +605,10 @@ SlabGetChunkSpace(void *pointer) { MemoryChunk *chunk = PointerGetMemoryChunk(pointer); SlabBlock *block = MemoryChunkGetBlock(chunk); - SlabContext *slab = block->slab; + SlabContext *slab; - Assert(slab); + AssertArg(SlabBlockIsValid(block)); + slab = block->slab; return slab->fullChunkSize; } @@ -591,9 +620,9 @@ SlabGetChunkSpace(void *pointer) bool SlabIsEmpty(MemoryContext context) { - SlabContext *slab = castNode(SlabContext, context); + SlabContext *slab = (SlabContext *) context; - Assert(slab); + AssertArg(SlabIsValid(slab)); return (slab->nblocks == 0); } @@ -613,13 +642,15 @@ SlabStats(MemoryContext context, MemoryContextCounters *totals, bool print_to_stderr) { - SlabContext *slab = castNode(SlabContext, context); + SlabContext *slab = (SlabContext *) context; Size nblocks = 0; Size freechunks = 0; Size totalspace; Size freespace = 0; int i; + AssertArg(SlabIsValid(slab)); + /* Include context header in totalspace */ totalspace = slab->headerSize; @@ -672,11 +703,11 @@ SlabStats(MemoryContext context, void SlabCheck(MemoryContext context) { + SlabContext *slab = (SlabContext *) context; int i; - SlabContext *slab = castNode(SlabContext, context); const char *name = slab->header.name; - Assert(slab); + AssertArg(SlabIsValid(slab)); Assert(slab->chunksPerBlock > 0); /* walk all the freelists */
^ permalink raw reply [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-10 20:54  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 152+ messages in thread

From: David Rowley @ 2022-10-10 20:54 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 11 Oct 2022 at 08:35, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Hearing no comments on that, I decided that a good policy would be
> to use Asserts in the paths dealing with small chunks but test-and-elog
> in the paths dealing with large chunks.

This seems like a good policy.  I think it's good to get at least the
Asserts in there. If we have any troubles in the future then we can
revisit this and reconsider if we need to elog them instead.

> Hence v2 attached, which cleans things up a tad in aset.c and then
> extends similar policy to generation.c and slab.c.

Looking at your changes to SlabFree(), I don't really think that
change is well aligned to the newly proposed policy. My understanding
of the rationale behind this policy is that large chunks get malloced
and will be slower anyway, so the elog(ERROR) is less overhead for
those.  In SlabFree(), we're most likely not doing any free()s, so I
don't quite understand why you've added the elog rather than the
Assert for this case. The slab allocator *should* be very fast.

I don't have any issue with any of the other changes.

David





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-10 21:07  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  0 siblings, 1 reply; 152+ messages in thread

From: Tom Lane @ 2022-10-10 21:07 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> Looking at your changes to SlabFree(), I don't really think that
> change is well aligned to the newly proposed policy. My understanding
> of the rationale behind this policy is that large chunks get malloced
> and will be slower anyway, so the elog(ERROR) is less overhead for
> those.  In SlabFree(), we're most likely not doing any free()s, so I
> don't quite understand why you've added the elog rather than the
> Assert for this case. The slab allocator *should* be very fast.

Yeah, slab.c hasn't any distinction between large and small chunks,
so we have to just pick one policy or the other.  I'd hoped to get
away with the more robust runtime test on the basis that slab allocation
is not used so much that this'd result in any noticeable performance
change.  SlabRealloc, at least, is not used *at all* per the code
coverage tests, and if we're there at all we should be highly suspicious
that something is wrong.  However, I could be wrong about SlabFree,
and if you're going to hold my feet to the fire then I'll change it
rather than try to produce some performance evidence.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-10 22:30  David Rowley <dgrowleyml@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 2 replies; 152+ messages in thread

From: David Rowley @ 2022-10-10 22:30 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, 11 Oct 2022 at 10:07, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Yeah, slab.c hasn't any distinction between large and small chunks,
> so we have to just pick one policy or the other.  I'd hoped to get
> away with the more robust runtime test on the basis that slab allocation
> is not used so much that this'd result in any noticeable performance
> change.  SlabRealloc, at least, is not used *at all* per the code
> coverage tests, and if we're there at all we should be highly suspicious
> that something is wrong.  However, I could be wrong about SlabFree,
> and if you're going to hold my feet to the fire then I'll change it
> rather than try to produce some performance evidence.

The main reason I brought it up was that only yesterday I was looking
into fixing the slowness of the Slab allocator. It's currently quite
far behind the performance of both generation.c and aset.c and it
would be very nice to bring it up to at least be on-par with those.
Ideally there would be some performance advantages of the fixed-sized
chunks. I'd just rather not have any additional things go in to make
that goal harder to reach.

The proposed patches in [1] do aim to make additional usages of the
slab allocator, and I have a feeling that we'll want to fix the
performance of slab.c before those. Perhaps the Asserts are a better
option if we're to get the proposed radix tree implementation.

David

[1] https://postgr.es/m/CAD21AoD3w76wERs_Lq7_uA6+gTaoOERPji+Yz8Ac6aui4JwvTg@mail.gmail.com





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-10 22:42  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 0 replies; 152+ messages in thread

From: Tom Lane @ 2022-10-10 22:42 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

David Rowley <dgrowleyml@gmail.com> writes:
> The main reason I brought it up was that only yesterday I was looking
> into fixing the slowness of the Slab allocator. It's currently quite
> far behind the performance of both generation.c and aset.c and it
> would be very nice to bring it up to at least be on-par with those.

Really!?  That's pretty sad, because surely it should be handling a
simpler case.

Anyway, I'm about to push this with an Assert in SlabFree and
run-time test in SlabRealloc.  That should be enough to assuage
my safety concerns, and then we can think about better performance.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-11 03:21  John Naylor <john.naylor@enterprisedb.com>
  parent: David Rowley <dgrowleyml@gmail.com>
  1 sibling, 1 reply; 152+ messages in thread

From: John Naylor @ 2022-10-11 03:21 UTC (permalink / raw)
  To: David Rowley <dgrowleyml@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Tue, Oct 11, 2022 at 5:31 AM David Rowley <dgrowleyml@gmail.com> wrote:
>
> The proposed patches in [1] do aim to make additional usages of the
> slab allocator, and I have a feeling that we'll want to fix the
> performance of slab.c before those. Perhaps the Asserts are a better
> option if we're to get the proposed radix tree implementation.

Going by [1], that use case is not actually a natural fit for slab because
of memory fragmentation. The motivation to use slab there was that the
allocation sizes are just over a power of two, leading to a lot of wasted
space for aset. FWIW, I have proposed in that thread a scheme to squeeze
things into power-of-two sizes without wasting quite as much space. That's
not a done deal, of course, but it could work today without adding memory
management code.

[1]
https://www.postgresql.org/message-id/20220704220038.at2ane5xkymzzssb%40awork3.anarazel.de

--
John Naylor
EDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-19 18:55  Andres Freund <andres@anarazel.de>
  parent: John Naylor <john.naylor@enterprisedb.com>
  0 siblings, 1 reply; 152+ messages in thread

From: Andres Freund @ 2022-10-19 18:55 UTC (permalink / raw)
  To: John Naylor <john.naylor@enterprisedb.com>; +Cc: David Rowley <dgrowleyml@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2022-10-11 10:21:17 +0700, John Naylor wrote:
> On Tue, Oct 11, 2022 at 5:31 AM David Rowley <dgrowleyml@gmail.com> wrote:
> >
> > The proposed patches in [1] do aim to make additional usages of the
> > slab allocator, and I have a feeling that we'll want to fix the
> > performance of slab.c before those. Perhaps the Asserts are a better
> > option if we're to get the proposed radix tree implementation.
> 
> Going by [1], that use case is not actually a natural fit for slab because
> of memory fragmentation.
>
> [1]
> https://www.postgresql.org/message-id/20220704220038.at2ane5xkymzzssb%40awork3.anarazel.de

Not so sure about that - IIRC I made one slab for each different size class,
which seemed to work well and suit slab well?

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 152+ messages in thread

* Re: Reducing the chunk header sizes on all memory context types
@ 2022-10-24 09:56  John Naylor <john.naylor@enterprisedb.com>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 0 replies; 152+ messages in thread

From: John Naylor @ 2022-10-24 09:56 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: David Rowley <dgrowleyml@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Julien Rouhaud <rjuju123@gmail.com>; Robert Haas <robertmhaas@gmail.com>; Yura Sokolov <y.sokolov@postgrespro.ru>; PostgreSQL Developers <pgsql-hackers@lists.postgresql.org>

On Thu, Oct 20, 2022 at 1:55 AM Andres Freund <andres@anarazel.de> wrote:
>
> Hi,
>
> On 2022-10-11 10:21:17 +0700, John Naylor wrote:
> > On Tue, Oct 11, 2022 at 5:31 AM David Rowley <dgrowleyml@gmail.com>
wrote:
> > >
> > > The proposed patches in [1] do aim to make additional usages of the
> > > slab allocator, and I have a feeling that we'll want to fix the
> > > performance of slab.c before those. Perhaps the Asserts are a better
> > > option if we're to get the proposed radix tree implementation.
> >
> > Going by [1], that use case is not actually a natural fit for slab
because
> > of memory fragmentation.
> >
> > [1]
> >
https://www.postgresql.org/message-id/20220704220038.at2ane5xkymzzssb%40awork3.anarazel.de
>
> Not so sure about that - IIRC I made one slab for each different size
class,
> which seemed to work well and suit slab well?

If that's the case, then great! The linked message didn't give me that
impression, but I won't worry about it.

--
John Naylor
EDB: http://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 152+ messages in thread


end of thread, other threads:[~2022-10-24 09:56 UTC | newest]

Thread overview: 152+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2022-07-12 05:01 Reducing the chunk header sizes on all memory context types David Rowley <dgrowleyml@gmail.com>
2022-07-12 17:22 ` Yura Sokolov <y.sokolov@postgrespro.ru>
2022-07-12 17:44   ` Andres Freund <andres@anarazel.de>
2022-07-13 05:20     ` David Rowley <dgrowleyml@gmail.com>
2022-08-09 12:53       ` David Rowley <dgrowleyml@gmail.com>
2022-08-09 14:36         ` Robert Haas <robertmhaas@gmail.com>
2022-08-09 18:44           ` Andres Freund <andres@anarazel.de>
2022-08-09 19:21             ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-09 21:02               ` Andres Freund <andres@anarazel.de>
2022-08-09 21:23                 ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-09 21:28                   ` David Rowley <dgrowleyml@gmail.com>
2022-08-09 21:44                     ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-09 19:36             ` Alvaro Herrera <alvherre@alvh.no-ip.org>
2022-08-10 06:33             ` David Rowley <dgrowleyml@gmail.com>
2022-08-17 13:58               ` David Rowley <dgrowleyml@gmail.com>
2022-08-23 09:03                 ` David Rowley <dgrowleyml@gmail.com>
2022-08-26 05:16                   ` David Rowley <dgrowleyml@gmail.com>
2022-08-28 11:04                     ` David Rowley <dgrowleyml@gmail.com>
2022-08-28 22:39                       ` David Rowley <dgrowleyml@gmail.com>
2022-08-29 05:26                         ` David Rowley <dgrowleyml@gmail.com>
2022-08-29 09:37                           ` Amit Kapila <amit.kapila16@gmail.com>
2022-08-29 09:42                             ` David Rowley <dgrowleyml@gmail.com>
2022-08-29 11:10                             ` David Rowley <dgrowleyml@gmail.com>
2022-08-29 13:47                               ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-29 14:02                                 ` Amit Kapila <amit.kapila16@gmail.com>
2022-08-29 14:52                                   ` Tomas Vondra <tomas.vondra@enterprisedb.com>
2022-08-29 15:20                                     ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-29 15:25                                       ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-29 15:39                                         ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-30 03:01                                           ` David Rowley <dgrowleyml@gmail.com>
2022-08-30 03:15                                             ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-30 03:21                                               ` David Rowley <dgrowleyml@gmail.com>
2022-08-30 03:31                                                 ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-29 15:27                                       ` Tomas Vondra <tomas.vondra@enterprisedb.com>
2022-08-29 15:39                                         ` Tomas Vondra <tomas.vondra@enterprisedb.com>
2022-08-30 00:45                                           ` David Rowley <dgrowleyml@gmail.com>
2022-08-30 01:16                                             ` David Rowley <dgrowleyml@gmail.com>
2022-08-30 01:45                                               ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-30 01:58                                               ` Tomas Vondra <tomas.vondra@enterprisedb.com>
2022-08-30 02:29                                                 ` David Rowley <dgrowleyml@gmail.com>
2022-08-30 02:42                                                 ` David Rowley <dgrowleyml@gmail.com>
2022-09-01 03:15                                               ` David Rowley <dgrowleyml@gmail.com>
2022-09-01 04:06                                                 ` Tom Lane <tgl@sss.pgh.pa.us>
2022-09-01 04:08                                                   ` David Rowley <dgrowleyml@gmail.com>
2022-09-01 04:19                                                     ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-30 01:24                                             ` Tomas Vondra <tomas.vondra@enterprisedb.com>
2022-08-30 01:55                                               ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-30 02:12                                                 ` Tomas Vondra <tomas.vondra@enterprisedb.com>
2022-08-30 02:31                                                 ` David Rowley <dgrowleyml@gmail.com>
2022-08-30 09:05                                                   ` Tomas Vondra <tomas.vondra@enterprisedb.com>
2022-08-30 13:26                                                   ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-30 14:17                                                     ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-30 22:40                                                       ` David Rowley <dgrowleyml@gmail.com>
2022-08-31 20:53                                                         ` Tomas Vondra <tomas.vondra@enterprisedb.com>
2022-08-31 21:46                                                           ` David Rowley <dgrowleyml@gmail.com>
2022-09-01 00:12                                                             ` Tomas Vondra <tomas.vondra@enterprisedb.com>
2022-09-01 00:23                                                             ` Tom Lane <tgl@sss.pgh.pa.us>
2022-09-01 00:31                                                               ` David Rowley <dgrowleyml@gmail.com>
2022-09-01 00:46                                                                 ` Tom Lane <tgl@sss.pgh.pa.us>
2022-09-02 08:11                                                                   ` David Rowley <dgrowleyml@gmail.com>
2022-09-05 13:41                                                                     ` David Rowley <dgrowleyml@gmail.com>
2022-09-07 04:13                                                                       ` David Rowley <dgrowleyml@gmail.com>
2022-09-07 04:56                                                                         ` Tom Lane <tgl@sss.pgh.pa.us>
2022-09-07 07:15                                                                         ` Yura Sokolov <y.sokolov@postgrespro.ru>
2022-09-01 00:49                                                               ` Tomas Vondra <tomas.vondra@enterprisedb.com>
2022-09-01 01:06                                                               ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-29 15:43                                       ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-29 15:57                                         ` Andres Freund <andres@anarazel.de>
2022-08-29 16:00                                           ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-29 16:00                                         ` Tomas Vondra <tomas.vondra@enterprisedb.com>
2022-08-29 21:55                                         ` David Rowley <dgrowleyml@gmail.com>
2022-08-29 21:57                                         ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-30 00:22                                           ` Tomas Vondra <tomas.vondra@enterprisedb.com>
2022-08-30 01:04                                             ` David Rowley <dgrowleyml@gmail.com>
2022-08-30 08:33                                               ` Tomas Vondra <tomas.vondra@enterprisedb.com>
2022-08-29 14:55                                   ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-29 15:15                                     ` Robert Haas <robertmhaas@gmail.com>
2022-08-29 15:31                                       ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-30 07:14                                       ` David Rowley <dgrowleyml@gmail.com>
2022-08-30 13:36                                         ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-30 15:31                                           ` David Rowley <dgrowleyml@gmail.com>
2022-08-30 15:39                                             ` David Rowley <dgrowleyml@gmail.com>
2022-08-30 15:54                                               ` Robert Haas <robertmhaas@gmail.com>
2022-08-30 16:17                                               ` Tom Lane <tgl@sss.pgh.pa.us>
2022-08-30 15:00                                         ` Robert Haas <robertmhaas@gmail.com>
2022-08-30 15:25                                           ` David Rowley <dgrowleyml@gmail.com>
2022-09-05 23:09                           ` Andres Freund <andres@anarazel.de>
2022-09-06 00:10                             ` David Rowley <dgrowleyml@gmail.com>
2022-09-06 00:27                               ` Tom Lane <tgl@sss.pgh.pa.us>
2022-09-06 02:32                                 ` David Rowley <dgrowleyml@gmail.com>
2022-09-06 02:35                                   ` David Rowley <dgrowleyml@gmail.com>
2022-09-06 02:43                                   ` Tom Lane <tgl@sss.pgh.pa.us>
2022-09-06 03:17                                     ` David Rowley <dgrowleyml@gmail.com>
2022-09-07 12:29                                       ` David Rowley <dgrowleyml@gmail.com>
2022-09-07 13:05                                         ` Julien Rouhaud <rjuju123@gmail.com>
2022-09-07 13:22                                           ` David Rowley <dgrowleyml@gmail.com>
2022-09-07 13:55                                             ` David Rowley <dgrowleyml@gmail.com>
2022-09-07 15:08                                               ` Tom Lane <tgl@sss.pgh.pa.us>
2022-09-07 21:32                                                 ` David Rowley <dgrowleyml@gmail.com>
2022-09-08 00:13                                                   ` David Rowley <dgrowleyml@gmail.com>
2022-09-08 16:44                                                 ` Andres Freund <andres@anarazel.de>
2022-09-08 18:10                                                   ` Tom Lane <tgl@sss.pgh.pa.us>
2022-09-08 22:15                                                     ` Andres Freund <andres@anarazel.de>
2022-09-08 22:53                                                       ` Tom Lane <tgl@sss.pgh.pa.us>
2022-09-08 23:33                                                         ` David Rowley <dgrowleyml@gmail.com>
2022-09-13 08:27                                                           ` David Rowley <dgrowleyml@gmail.com>
2022-09-20 01:11                                                             ` David Rowley <dgrowleyml@gmail.com>
2022-09-20 01:23                                                               ` Tom Lane <tgl@sss.pgh.pa.us>
2022-09-20 04:49                                                                 ` David Rowley <dgrowleyml@gmail.com>
2022-09-20 05:23                                                                   ` Tom Lane <tgl@sss.pgh.pa.us>
2022-09-20 06:10                                                                     ` David Rowley <dgrowleyml@gmail.com>
2022-09-26 22:28                                                                 ` David Rowley <dgrowleyml@gmail.com>
2022-09-29 05:30                                                                   ` David Rowley <dgrowleyml@gmail.com>
2022-10-02 23:43                                                                     ` David Rowley <dgrowleyml@gmail.com>
2022-10-03 19:37                                                                       ` Tom Lane <tgl@sss.pgh.pa.us>
2022-10-04 15:55                                                                         ` Tom Lane <tgl@sss.pgh.pa.us>
2022-10-06 04:59                                                                           ` David Rowley <dgrowleyml@gmail.com>
2022-10-06 15:37                                                                             ` Tom Lane <tgl@sss.pgh.pa.us>
2022-10-06 17:38                                                                             ` Tom Lane <tgl@sss.pgh.pa.us>
2022-10-06 18:19                                                                               ` Tom Lane <tgl@sss.pgh.pa.us>
2022-10-06 19:00                                                                                 ` Andres Freund <andres@anarazel.de>
2022-10-06 19:10                                                                                   ` Tom Lane <tgl@sss.pgh.pa.us>
2022-10-06 19:14                                                                                     ` Andres Freund <andres@anarazel.de>
2022-10-06 19:23                                                                                       ` Tom Lane <tgl@sss.pgh.pa.us>
2022-10-06 20:05                                                                                         ` Tom Lane <tgl@sss.pgh.pa.us>
2022-10-06 20:44                                                                                           ` David Rowley <dgrowleyml@gmail.com>
2022-10-06 20:54                                                                                             ` Tom Lane <tgl@sss.pgh.pa.us>
2022-10-06 21:57                                                                                           ` Tom Lane <tgl@sss.pgh.pa.us>
2022-10-06 22:38                                                                                             ` David Rowley <dgrowleyml@gmail.com>
2022-10-06 23:10                                                                                             ` Tom Lane <tgl@sss.pgh.pa.us>
2022-10-06 23:35                                                                                               ` Tom Lane <tgl@sss.pgh.pa.us>
2022-10-07 00:50                                                                                                 ` David Rowley <dgrowleyml@gmail.com>
2022-10-07 01:00                                                                                                   ` Tom Lane <tgl@sss.pgh.pa.us>
2022-10-08 15:52                                                                                                     ` Tom Lane <tgl@sss.pgh.pa.us>
2022-10-10 19:35                                                                                                       ` Tom Lane <tgl@sss.pgh.pa.us>
2022-10-10 20:54                                                                                                         ` David Rowley <dgrowleyml@gmail.com>
2022-10-10 21:07                                                                                                           ` Tom Lane <tgl@sss.pgh.pa.us>
2022-10-10 22:30                                                                                                             ` David Rowley <dgrowleyml@gmail.com>
2022-10-10 22:42                                                                                                               ` Tom Lane <tgl@sss.pgh.pa.us>
2022-10-11 03:21                                                                                                               ` John Naylor <john.naylor@enterprisedb.com>
2022-10-19 18:55                                                                                                                 ` Andres Freund <andres@anarazel.de>
2022-10-24 09:56                                                                                                                   ` John Naylor <john.naylor@enterprisedb.com>
2022-08-09 23:17           ` David Rowley <dgrowleyml@gmail.com>
2022-07-12 17:42 ` Andres Freund <andres@anarazel.de>
2022-07-13 05:24   ` David Rowley <dgrowleyml@gmail.com>
2022-07-13 05:41   ` Andres Freund <andres@anarazel.de>
2022-07-17 16:10     ` Yura Sokolov <y.sokolov@postgrespro.ru>
2022-09-01 13:27 Re: Reducing the chunk header sizes on all memory context types Ranier Vilela <ranier.vf@gmail.com>
2022-10-04 00:35 Re: Reducing the chunk header sizes on all memory context types Ranier Vilela <ranier.vf@gmail.com>
2022-10-04 08:35 ` David Rowley <dgrowleyml@gmail.com>
2022-10-04 11:29   ` Ranier Vilela <ranier.vf@gmail.com>
2022-10-04 12:25     ` Ranier Vilela <ranier.vf@gmail.com>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox