/* Build a dsa_pointer given a segment number and offset. */ #define DSA_MAKE_POINTER(segment_number, offset) \
(((dsa_pointer) (segment_number) << DSA_OFFSET_WIDTH) | (offset))
/* Extract the segment number from a dsa_pointer. */ #define DSA_EXTRACT_SEGMENT_NUMBER(dp) ((dp) >> DSA_OFFSET_WIDTH)
/* Extract the offset from a dsa_pointer. */ #define DSA_EXTRACT_OFFSET(dp) ((dp) & DSA_OFFSET_BITMASK)
/* The type used for index segment indexes (zero based). */ typedef size_t dsa_segment_index;
/* Sentinel value for dsa_segment_index indicating 'none' or 'end'. */ #define DSA_SEGMENT_INDEX_NONE (~(dsa_segment_index)0)
if (n == 0)
bin = 0; else
bin = pg_leftmost_one_pos_size_t(n) + 1;
return Min(bin, DSA_NUM_SEGMENT_BINS - 1);
}
/* Macros for access to locks. */ #define DSA_AREA_LOCK(area) (&area->control->lock) #define DSA_SCLASS_LOCK(area, sclass) (&area->control->pools[sclass].lock)
/* *Theheaderforanindividualsegment.ThislivesatthestartofeachDSM *segmentownedbyaDSAareaincludingthefirstsegment(whereitappears *aspartofthedsa_area_controlstruct).
*/ typedefstruct
{ /* Sanity check magic value. */
uint32 magic; /* Total number of pages in this segment (excluding metadata area). */
size_t usable_pages; /* Total size of this segment in bytes. */
size_t size;
/* *Indexofthesegmentthatfollowsthisoneinthesamesegmentbin,or *DSA_SEGMENT_INDEX_NONEifthisisthelastone.
*/
dsa_segment_index next; /* The index of the bin that contains this segment. */
size_t bin;
/* *Adsa_area_poolrepresentsasetofobjectsofagivensizeclass. * *Perhapsthereshouldbemultiplepoolsforthesamesizeclassfor *contentionavoidance,butfornowthereisjustone!
*/ typedefstruct
{ /* A lock protecting access to this pool. */
LWLock lock; /* A set of linked lists of spans, arranged by fullness. */
dsa_pointer spans[DSA_FULLNESS_CLASSES]; /* Should we pad this out to a cacheline boundary? */
} dsa_area_pool;
/* *Thecontrolblockforanarea.Thislivesinsharedmemory,atthestartof *thefirstDSMsegmentcontrolledbythisarea.
*/ typedefstruct
{ /* The segment header for the first segment. */
dsa_segment_header segment_header; /* The handle for this area. */
dsa_handle handle; /* The handles of the segments owned by this area. */
dsm_handle segment_handles[DSA_MAX_SEGMENTS]; /* Lists of segments, binned by maximum contiguous run of free pages. */
dsa_segment_index segment_bins[DSA_NUM_SEGMENT_BINS]; /* The object pools for each size class. */
dsa_area_pool pools[DSA_NUM_SIZE_CLASSES]; /* initial allocation segment size */
size_t init_segment_size; /* maximum allocation segment size */
size_t max_segment_size; /* The total size of all active segments. */
size_t total_segment_size; /* The maximum total size of backing storage we are allowed. */
size_t max_total_segment_size; /* Highest used segment index in the history of this area. */
dsa_segment_index high_segment_index; /* The reference count for this area. */ int refcnt; /* A flag indicating that this area has been pinned. */ bool pinned; /* The number of times that segments have been freed. */
size_t freed_segment_counter; /* The LWLock tranche ID. */ int lwlock_tranche_id; /* The general lock (protects everything except object pools). */
LWLock lock;
} dsa_area_control;
/* Given a pointer to a pool, find a dsa_pointer. */ #define DsaAreaPoolToDsaPointer(area, p) \
DSA_MAKE_POINTER(0, (char *) p - (char *) area->control)
/* *Adsa_segment_mapisstoredwithinthebackend-privatememoryofeach *individualbackend.Itholdsthebaseaddressofthesegmentwithinthat *backend,plustheaddressesofkeyobjectswithinthesegment.Those *couldinsteadbederivedfromthebaseaddressbutit'shandytohavethem *around.
*/ typedefstruct
{
dsm_segment *segment; /* DSM segment */ char *mapped_address; /* Address at which segment is mapped */
dsa_segment_header *header; /* Header (same as mapped_address) */
FreePageManager *fpm; /* Free page manager within segment. */
dsa_pointer *pagemap; /* Page map within segment. */
} dsa_segment_map;
/* *Per-backendstateforastoragearea.Backendsobtainoneoftheseby *creatinganareaorattachingtoanexistingoneusingahandle.Each *processthatneedstouseanareausesitsownobjecttotrackwherethe *segmentsaremapped.
*/ struct dsa_area
{ /* Pointer to the control object in shared memory. */
dsa_area_control *control;
/* Given a pointer to a segment_map, obtain a segment index number. */ #define get_segment_index(area, segment_map_ptr) \
(segment_map_ptr - &area->segment_maps[0])
/* Create a new DSA area with the control object in this segment. */
area = create_internal(dsm_segment_address(segment),
init_segment_size,
tranche_id,
dsm_segment_handle(segment), segment,
init_segment_size, max_segment_size);
/* Clean up when the control segment detaches. */
on_dsm_detach(segment, &dsa_on_dsm_detach_release_in_place,
PointerGetDatum(dsm_segment_address(segment)));
/* *AnareahandleisreallyaDSMsegmenthandleforthefirstsegment,so *wegoaheadandattachtothat.
*/
segment = dsm_attach(handle); if (segment == NULL)
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("could not attach to dynamic shared area")));
area = attach_internal(dsm_segment_address(segment), segment, handle);
/* Clean up when the control segment detaches. */
on_dsm_detach(segment, &dsa_on_dsm_detach_release_in_place,
PointerGetDatum(dsm_segment_address(segment)));
/* Obtain a span object. */
span_pointer = alloc_object(area, DSA_SCLASS_BLOCK_OF_SPANS); if (!DsaPointerIsValid(span_pointer))
{ /* Raise error unless asked not to. */ if ((flags & DSA_ALLOC_NO_OOM) == 0)
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory"),
errdetail("Failed on DSA request of size %zu.",
size))); return InvalidDsaPointer;
}
LWLockAcquire(DSA_AREA_LOCK(area), LW_EXCLUSIVE);
/* Find a segment from which to allocate. */
segment_map = get_best_segment(area, npages); if (segment_map == NULL)
segment_map = make_new_segment(area, npages); if (segment_map == NULL)
{ /* Can't make any more segments: game over. */
LWLockRelease(DSA_AREA_LOCK(area));
dsa_free(area, span_pointer);
/* Raise error unless asked not to. */ if ((flags & DSA_ALLOC_NO_OOM) == 0)
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory"),
errdetail("Failed on DSA request of size %zu.",
size))); return InvalidDsaPointer;
}
/* *Askthefreepagemanagerforarunofpages.Thisshouldalways *succeed,sincebothget_best_segmentandmake_new_segmentshould *onlyreturnanon-NULLpointerifitactuallycontainsenough *contiguousfreespace.Ifitdoesfail,somethinginourbackend *privatestateisoutofwhack,souseFATALtokilltheprocess.
*/ if (!FreePageManagerGet(segment_map->fpm, npages, &first_page))
elog(FATAL, "dsa_allocate could not find %zu free pages", npages);
LWLockRelease(DSA_AREA_LOCK(area));
/* Attempt to allocate an object from the appropriate pool. */
result = alloc_object(area, size_class);
/* Check for failure to allocate. */ if (!DsaPointerIsValid(result))
{ /* Raise error unless asked not to. */ if ((flags & DSA_ALLOC_NO_OOM) == 0)
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory"),
errdetail("Failed on DSA request of size %zu.", size))); return InvalidDsaPointer;
}
/* Zero-initialize the memory if requested. */ if ((flags & DSA_ALLOC_ZERO) != 0)
memset(dsa_get_address(area, result), 0, size);
/* Convert InvalidDsaPointer to NULL. */ if (!DsaPointerIsValid(dp)) return NULL;
/* Process any requests to detach from freed segments. */
check_for_freed_segments(area);
/* Break the dsa_pointer into its components. */
index = DSA_EXTRACT_SEGMENT_NUMBER(dp);
offset = DSA_EXTRACT_OFFSET(dp);
Assert(index < DSA_MAX_SEGMENTS);
/* Check if we need to cause this segment to be mapped in. */ if (unlikely(area->segment_maps[index].mapped_address == NULL))
{ /* Call for effect (we don't need the result). */
get_segment_by_index(area, index);
}
if (i == 0)
fprintf(stderr, " segment bin %zu (no contiguous free pages):\n", i); else
fprintf(stderr, " segment bin %zu (at least %d contiguous pages free):\n",
i, 1 << (i - 1));
segment_index = area->control->segment_bins[i]; while (segment_index != DSA_SEGMENT_INDEX_NONE)
{
dsa_segment_map *segment_map;
fprintf(stderr, " pools:\n"); for (i = 0; i < DSA_NUM_SIZE_CLASSES; ++i)
{ bool found = false;
LWLockAcquire(DSA_SCLASS_LOCK(area, i), LW_EXCLUSIVE); for (j = 0; j < DSA_FULLNESS_CLASSES; ++j) if (DsaPointerIsValid(area->control->pools[i].spans[j]))
found = true; if (found)
{ if (i == DSA_SCLASS_BLOCK_OF_SPANS)
fprintf(stderr, " pool for blocks of span objects:\n"); elseif (i == DSA_SCLASS_SPAN_LARGE)
fprintf(stderr, " pool for large object spans:\n"); else
fprintf(stderr, " pool for size class %zu (object size %hu bytes):\n",
i, dsa_size_classes[i]); for (j = 0; j < DSA_FULLNESS_CLASSES; ++j)
{ if (!DsaPointerIsValid(area->control->pools[i].spans[j]))
fprintf(stderr, " fullness class %zu is empty\n", j); else
{
dsa_pointer span_pointer = area->control->pools[i].spans[j];
fprintf(stderr, " fullness class %zu:\n", j); while (DsaPointerIsValid(span_pointer))
{
dsa_area_span *span;
/* Figure out how many pages we need, including the page map... */ while (((size + FPM_PAGE_SIZE - 1) / FPM_PAGE_SIZE) > pages)
{
++pages;
size += sizeof(dsa_pointer);
}
/* Check the initial and maximum block sizes */
Assert(init_segment_size >= DSA_MIN_SEGMENT_SIZE);
Assert(max_segment_size >= init_segment_size);
Assert(max_segment_size <= DSA_MAX_SEGMENT_SIZE);
/* Sanity check on the space we have to work in. */ if (size < dsa_minimum_size())
elog(ERROR, "dsa_area space must be at least %zu, but %zu provided",
dsa_minimum_size(), size);
/* Now figure out how much space is usable */
total_pages = size / FPM_PAGE_SIZE;
metadata_bytes =
MAXALIGN(sizeof(dsa_area_control)) +
MAXALIGN(sizeof(FreePageManager)) +
total_pages * sizeof(dsa_pointer); /* Add padding up to next page boundary. */ if (metadata_bytes % FPM_PAGE_SIZE != 0)
metadata_bytes += FPM_PAGE_SIZE - (metadata_bytes % FPM_PAGE_SIZE);
Assert(metadata_bytes <= size);
usable_pages = (size - metadata_bytes) / FPM_PAGE_SIZE;
/* *Createthedsa_areaobjectthatthisbackendwillusetoaccessthe *area.Otherbackendswillneedtoobtaintheirowndsa_areaobjectby *attaching.
*/
area = palloc(sizeof(dsa_area));
area->control = control;
area->resowner = CurrentResourceOwner;
memset(area->segment_maps, 0, sizeof(dsa_segment_map) * DSA_MAX_SEGMENTS);
area->high_segment_index = 0;
area->freed_segment_counter = 0;
LWLockInitialize(&control->lock, control->lwlock_tranche_id); for (i = 0; i < DSA_NUM_SIZE_CLASSES; ++i)
LWLockInitialize(DSA_SCLASS_LOCK(area, i),
control->lwlock_tranche_id);
/* Set up the segment map for this process's mapping. */
segment_map = &area->segment_maps[0];
segment_map->segment = control_segment;
segment_map->mapped_address = place;
segment_map->header = (dsa_segment_header *) place;
segment_map->fpm = (FreePageManager *)
(segment_map->mapped_address +
MAXALIGN(sizeof(dsa_area_control)));
segment_map->pagemap = (dsa_pointer *)
(segment_map->mapped_address +
MAXALIGN(sizeof(dsa_area_control)) +
MAXALIGN(sizeof(FreePageManager)));
/* Set up the free page map. */
FreePageManagerInitialize(segment_map->fpm, segment_map->mapped_address); /* There can be 0 usable pages if size is dsa_minimum_size(). */
if (usable_pages > 0)
FreePageManagerPut(segment_map->fpm, metadata_bytes / FPM_PAGE_SIZE,
usable_pages);
/* Put this segment into the appropriate bin. */
control->segment_bins[contiguous_pages_to_segment_bin(usable_pages)] = 0;
segment_map->header->bin = contiguous_pages_to_segment_bin(usable_pages);
/* Build the backend-local area object. */
area = palloc(sizeof(dsa_area));
area->control = control;
area->resowner = CurrentResourceOwner;
memset(&area->segment_maps[0], 0, sizeof(dsa_segment_map) * DSA_MAX_SEGMENTS);
area->high_segment_index = 0;
/* Set up the segment map for this process's mapping. */
segment_map = &area->segment_maps[0];
segment_map->segment = segment; /* NULL for in-place */
segment_map->mapped_address = place;
segment_map->header = (dsa_segment_header *) segment_map->mapped_address;
segment_map->fpm = (FreePageManager *)
(segment_map->mapped_address + MAXALIGN(sizeof(dsa_area_control)));
segment_map->pagemap = (dsa_pointer *)
(segment_map->mapped_address + MAXALIGN(sizeof(dsa_area_control)) +
MAXALIGN(sizeof(FreePageManager)));
/* Bump the reference count. */
LWLockAcquire(DSA_AREA_LOCK(area), LW_EXCLUSIVE); if (control->refcnt == 0)
{ /* We can't attach to a DSA area that has already been destroyed. */
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("could not attach to dynamic shared area")));
}
++control->refcnt;
area->freed_segment_counter = area->control->freed_segment_counter;
LWLockRelease(DSA_AREA_LOCK(area));
/* Push this span onto the front of the span list for fullness class 1. */ if (DsaPointerIsValid(pool->spans[1]))
{
dsa_area_span *head = (dsa_area_span *)
dsa_get_address(area, pool->spans[1]);
/* If it's now full, move it to the highest-numbered fullness class. */ if (span->nallocatable == 0)
transfer_first_span(area, pool, 1, DSA_FULLNESS_CLASSES - 1);
}
/* Figure out what fullness class should contain this span. */
tfclass = (nmax - span->nallocatable)
* (DSA_FULLNESS_CLASSES - 1) / nmax;
/* Look up next span. */ if (DsaPointerIsValid(span->nextspan))
nextspan = (dsa_area_span *)
dsa_get_address(area, span->nextspan); else
nextspan = NULL;
/* *Ifutilizationhasdroppedenoughthatthisnowbelongsinsome *otherfullnessclass,moveitthere.
*/ if (tfclass < fclass)
{ /* Remove from the current fullness class list. */ if (pool->spans[fclass] == span_pointer)
{ /* It was the head; remove it. */
Assert(!DsaPointerIsValid(span->prevspan));
pool->spans[fclass] = span->nextspan; if (nextspan != NULL)
nextspan->prevspan = InvalidDsaPointer;
} else
{ /* It was not the head. */
Assert(DsaPointerIsValid(span->prevspan));
prevspan = (dsa_area_span *)
dsa_get_address(area, span->prevspan);
prevspan->nextspan = span->nextspan;
} if (nextspan != NULL)
nextspan->prevspan = span->prevspan;
/* Push onto the head of the new fullness class list. */
span->nextspan = pool->spans[tfclass];
pool->spans[tfclass] = span_pointer;
span->prevspan = InvalidDsaPointer; if (DsaPointerIsValid(span->nextspan))
{
nextspan = (dsa_area_span *)
dsa_get_address(area, span->nextspan);
nextspan->prevspan = span_pointer;
}
span->fclass = tfclass;
}
/* Advance to next span on list. */
span_pointer = next_span_pointer;
}
/* Stop now if we found a suitable block. */ if (DsaPointerIsValid(pool->spans[1])) returntrue;
}
/* *Iftherearenoblocksthatproperlybelonginfullnessclass1,pick *onefromsomeotherfullnessclassandmoveitthereanyway,sothatwe *haveanallocationtarget.Ourlastchoiceistotransferablock *that'salmostempty(andmightbecomecompletelyemptysoonifleft *alone),buteventhatisbetterthanfailing,whichiswhatwemustdo *iftherearenoblocksatallwithfreespace.
*/
Assert(!DsaPointerIsValid(pool->spans[1])); for (fclass = 2; fclass < DSA_FULLNESS_CLASSES - 1; ++fclass) if (transfer_first_span(area, pool, fclass, 1)) returntrue; if (!DsaPointerIsValid(pool->spans[1]) &&
transfer_first_span(area, pool, 0, 1)) returntrue;
/* Find or create a segment and allocate the superblock. */
LWLockAcquire(DSA_AREA_LOCK(area), LW_EXCLUSIVE);
segment_map = get_best_segment(area, npages); if (segment_map == NULL)
{
segment_map = make_new_segment(area, npages); if (segment_map == NULL)
{
LWLockRelease(DSA_AREA_LOCK(area)); returnfalse;
}
}
/* *Thisshouldn'thappen:get_best_segment()ormake_new_segment() *promisedthatwecansuccessfullyallocatenpages.
*/ if (!FreePageManagerGet(segment_map->fpm, npages, &first_page))
elog(FATAL, "dsa_allocate could not find %zu free pages for superblock",
npages);
LWLockRelease(DSA_AREA_LOCK(area));
/* Compute the start of the superblock. */
start_pointer =
DSA_MAKE_POINTER(get_segment_index(area, segment_map),
first_page * FPM_PAGE_SIZE);
/* Initialize span and pagemap. */
init_span(area, span_pointer, pool, start_pointer, npages, size_class); for (i = 0; i < npages; ++i)
segment_map->pagemap[first_page + i] = span_pointer;
/* It's an error to try to access an unused slot. */ if (handle == DSM_HANDLE_INVALID)
elog(ERROR, "dsa_area could not attach to a segment that has been freed");
/*
* Detach from an area that was either created or attached to by this process.
*/
void
dsa_detach(dsa_area *area)
{
int i;
/* Detach from all segments. */ for (i = 0; i <= area->high_segment_index; ++i) if (area->segment_maps[i].segment != NULL)
dsm_detach(area->segment_maps[i].segment);
/*
* Note that 'detaching' (= detaching from DSM segments) doesn't include
* 'releasing' (= adjusting the reference count). It would be nice to
* combine these operations, but client code might never get around to
* calling dsa_detach because of an error path, and a detach hook on any
* particular segment is too late to detach other segments in the area
* without risking a 'leak' warning in the non-error path.
*/
/* Free the backend-local area object. */
pfree(area);
}
/*
* Unlink a segment from the bin that contains it.
*/
static void
unlink_segment(dsa_area *area, dsa_segment_map *segment_map)
{ if (segment_map->header->prev != DSA_SEGMENT_INDEX_NONE)
{
dsa_segment_map *prev;
next = get_segment_by_index(area, segment_map->header->next);
next->header->prev = segment_map->header->prev;
}
}
/*
* Find a segment that could satisfy a request for'npages'of contiguous
* memory, or return NULL if none can be found. This may involve attaching to
* segments that weren't previously attached so that we can query their free
* pages map.
*/
static dsa_segment_map *
get_best_segment(dsa_area *area, size_t npages)
{
size_t bin;
/*
* Start searching from the first bin that *might* have enough contiguous
* pages.
*/ for (bin = contiguous_pages_to_segment_bin(npages);
bin < DSA_NUM_SEGMENT_BINS;
++bin)
{
/*
* The minimum contiguous size that any segment in this bin should
* have. We'll re-bin if we see segments with fewer.
*/
size_t threshold = (size_t) 1 << (bin - 1);
dsa_segment_index segment_index;
/* Search this bin for a segment with enough contiguous space. */
segment_index = area->control->segment_bins[bin]; while (segment_index != DSA_SEGMENT_INDEX_NONE)
{
dsa_segment_map *segment_map;
dsa_segment_index next_segment_index;
size_t contiguous_pages;
/* Not enough for the request, still enough for this bin. */ if (contiguous_pages >= threshold && contiguous_pages < npages)
{
segment_index = next_segment_index;
continue;
}
/* Re-bin it if it's no longer in the appropriate bin. */ if (contiguous_pages < threshold)
{
rebin_segment(area, segment_map);
/*
* But fall through to see if it's enough to satisfy this
* request anyway....
*/
}
/* Check if we are done. */ if (contiguous_pages >= npages)
return segment_map;
/* Continue searching the same bin. */
segment_index = next_segment_index;
}
}
/* Not found. */
return NULL;
}
/*
* Create a new segment that can handle at least requested_pages. Returns
* NULL if the requested total size limit or maximum allowed number of
* segments would be exceeded.
*/
static dsa_segment_map *
make_new_segment(dsa_area *area, size_t requested_pages)
{
dsa_segment_index new_index;
size_t metadata_bytes;
size_t total_size;
size_t total_pages;
size_t usable_pages;
dsa_segment_map *segment_map;
dsm_segment *segment;
ResourceOwner oldowner;
Assert(LWLockHeldByMe(DSA_AREA_LOCK(area)));
/* Find a segment slot that isnotin use (linearly for now). */ for (new_index = 1; new_index < DSA_MAX_SEGMENTS; ++new_index)
{ if (area->control->segment_handles[new_index] == DSM_HANDLE_INVALID)
break;
} if (new_index == DSA_MAX_SEGMENTS)
return NULL;
/*
* If the total size limit is already exceeded, then we exit early and
* avoid arithmetic wraparound in the unsigned expressions below.
*/ if (area->control->total_segment_size >=
area->control->max_total_segment_size)
return NULL;
/*
* The size should be at least as big as requested, and at least big
* enough to follow a geometric series that approximately doubles the
* total storage each time we create a new segment. We use geometric
* growth because the underlying DSM system isn't designed for large
* numbers of segments (otherwise we might even consider just using one
* DSM segment for each large allocation andfor each superblock, andthen
* we wouldn't need to use FreePageManager).
*
* We decide on a total segment size first, so that we produce tidy
* power-of-two sized segments. This is a good propertyto have if we
* move to huge pages in the future. Then we work back to the number of
* pages we can fit.
*/
total_size = area->control->init_segment_size *
((size_t) 1 << (new_index / DSA_NUM_SEGMENTS_AT_EACH_SIZE));
total_size = Min(total_size, area->control->max_segment_size);
total_size = Min(total_size,
area->control->max_total_segment_size -
area->control->total_segment_size);
/* Add padding up to next page boundary. */ if (metadata_bytes % FPM_PAGE_SIZE != 0)
metadata_bytes += FPM_PAGE_SIZE - (metadata_bytes % FPM_PAGE_SIZE); if (total_size <= metadata_bytes)
return NULL;
usable_pages = (total_size - metadata_bytes) / FPM_PAGE_SIZE;
Assert(metadata_bytes + usable_pages * FPM_PAGE_SIZE <= total_size);
/* See if that is enough... */ if (requested_pages > usable_pages)
{
size_t total_requested_pages PG_USED_FOR_ASSERTS_ONLY;
/*
* We'll make an odd-sized segment, working forward from the requested
* number of pages.
*/
usable_pages = requested_pages;
metadata_bytes =
MAXALIGN(sizeof(dsa_segment_header)) +
MAXALIGN(sizeof(FreePageManager)) +
usable_pages * sizeof(dsa_pointer);
/*
* We must also account for pagemap entries needed to cover the
* metadata pages themselves. The pagemap must track all pages in the
* segment, including the pages occupied by metadata.
*
* This formula usesinteger ceiling division to compute the exact
* number of additional entries needed. The divisor (FPM_PAGE_SIZE -
* sizeof(dsa_pointer)) accounts for the fact that each metadata page
* consumes one pagemap entry of sizeof(dsa_pointer) bytes, leaving
* only (FPM_PAGE_SIZE - sizeof(dsa_pointer)) net bytes per metadata
* page.
*/
metadata_bytes +=
((metadata_bytes + (FPM_PAGE_SIZE - sizeof(dsa_pointer)) - 1) /
(FPM_PAGE_SIZE - sizeof(dsa_pointer))) *
sizeof(dsa_pointer);
/* Add padding up to next page boundary. */ if (metadata_bytes % FPM_PAGE_SIZE != 0)
metadata_bytes += FPM_PAGE_SIZE - (metadata_bytes % FPM_PAGE_SIZE);
total_size = metadata_bytes + usable_pages * FPM_PAGE_SIZE;
total_requested_pages = total_size / FPM_PAGE_SIZE;
/*
* Verify that we allocated enough pagemap entries for metadata and
* usable pages. This reverse-engineers the new calculation of
* "metadata_bytes" done based on the new "requested_pages"for an
* odd-sized segment.
*/
Assert((metadata_bytes - MAXALIGN(sizeof(dsa_segment_header)) -
MAXALIGN(sizeof(FreePageManager))) / sizeof(dsa_pointer) >= total_requested_pages);
/* Is that too large for dsa_pointer's addressing scheme? */ if (total_size > DSA_MAX_SEGMENT_SIZE)
return NULL;
/* Would that exceed the limit? */ if (total_size > area->control->max_total_segment_size -
area->control->total_segment_size)
return NULL;
}
/* Store the handle in shared memory to be found by index. */
area->control->segment_handles[new_index] =
dsm_segment_handle(segment);
/* Track the highest segment index in the history of the area. */ if (area->control->high_segment_index < new_index)
area->control->high_segment_index = new_index;
/* Track the highest segment index this backend has ever mapped. */ if (area->high_segment_index < new_index)
area->high_segment_index = new_index;
/* Track total size of all segments. */
area->control->total_segment_size += total_size;
Assert(area->control->total_segment_size <=
area->control->max_total_segment_size);
/* Build a segment map for this segment in this backend. */
segment_map = &area->segment_maps[new_index];
segment_map->segment = segment;
segment_map->mapped_address = dsm_segment_address(segment);
segment_map->header = (dsa_segment_header *) segment_map->mapped_address;
segment_map->fpm = (FreePageManager *)
(segment_map->mapped_address +
MAXALIGN(sizeof(dsa_segment_header)));
segment_map->pagemap = (dsa_pointer *)
(segment_map->mapped_address +
MAXALIGN(sizeof(dsa_segment_header)) +
MAXALIGN(sizeof(FreePageManager)));
/* Set up the free page map. */
FreePageManagerInitialize(segment_map->fpm, segment_map->mapped_address);
FreePageManagerPut(segment_map->fpm, metadata_bytes / FPM_PAGE_SIZE,
usable_pages);
/* Set up the segment header and put it in the appropriate bin. */
segment_map->header->magic =
DSA_SEGMENT_HEADER_MAGIC ^ area->control->handle ^ new_index;
segment_map->header->usable_pages = usable_pages;
segment_map->header->size = total_size;
segment_map->header->bin = contiguous_pages_to_segment_bin(usable_pages);
segment_map->header->prev = DSA_SEGMENT_INDEX_NONE;
segment_map->header->next =
area->control->segment_bins[segment_map->header->bin];
segment_map->header->freed = false;
area->control->segment_bins[segment_map->header->bin] = new_index; if (segment_map->header->next != DSA_SEGMENT_INDEX_NONE)
{
dsa_segment_map *next =
get_segment_by_index(area, segment_map->header->next);
/*
* Check if any segments have been freed by destroy_superblock, so we can
* detach from them in this backend. This functionis called by
* dsa_get_address and dsa_free to make sure that a dsa_pointer they have
* received can be resolved to the correct segment.
*
* The danger we want to defend against is that there could be an old segment
* mapped into a given slot in this backend, and the dsa_pointer they have
* might refer to some new segment in the same slot. So those functions must
* be sure to process all instructions to detach from a freed segment that had
* been generated by the time this process received the dsa_pointer, before
* they call get_segment_by_index.
*/
static void
check_for_freed_segments(dsa_area *area)
{
size_t freed_segment_counter;
/*
* Any other process that has freed a segment has incremented
* freed_segment_counter while holding an LWLock, and that must precede
* any backend creating a new segment in the same slot while holding an
* LWLock, and that must precede the creation of any dsa_pointer pointing
* into the new segment which might reach us here, and the caller must
* have sent the dsa_pointer to this process using appropriate memory
* synchronization (some kind of locking or atomic primitive or system
* call). So all we need todo on the reading side is ask for the load of
* freed_segment_counter to follow the caller's load of the dsa_pointer it
* has, and we can be sure to detect any segments that had been freed as
* of the time that the dsa_pointer reached this process.
*/
pg_read_barrier();
freed_segment_counter = area->control->freed_segment_counter; if (unlikely(area->freed_segment_counter != freed_segment_counter))
{
/* Check all currently mapped segments to find what's been freed. */
LWLockAcquire(DSA_AREA_LOCK(area), LW_EXCLUSIVE);
check_for_freed_segments_locked(area);
LWLockRelease(DSA_AREA_LOCK(area));
}
}
/*
* Workhorse for check_for_freed_segments(), and also used directly in path
* where the area lock is already held. This should be called after acquiring
* the lock but before looking up any segment by index number, to make sure we
* unmap any stale segments that might have previously had the same index as a
* current segment.
*/
static void
check_for_freed_segments_locked(dsa_area *area)
{
size_t freed_segment_counter;
int i;
Assert(LWLockHeldByMe(DSA_AREA_LOCK(area)));
freed_segment_counter = area->control->freed_segment_counter; if (unlikely(area->freed_segment_counter != freed_segment_counter))
{ for (i = 0; i <= area->high_segment_index; ++i)
{ if (area->segment_maps[i].header != NULL &&
area->segment_maps[i].header->freed)
{
dsm_detach(area->segment_maps[i].segment);
area->segment_maps[i].segment = NULL;
area->segment_maps[i].header = NULL;
area->segment_maps[i].mapped_address = NULL;
}
}
area->freed_segment_counter = freed_segment_counter;
}
}
/*
* Re-bin segment if it's no longer in the appropriate bin.
*/
static void
rebin_segment(dsa_area *area, dsa_segment_map *segment_map)
{
size_t new_bin;
dsa_segment_index segment_index;
new_bin = contiguous_pages_to_segment_bin(fpm_largest(segment_map->fpm)); if (segment_map->header->bin == new_bin)
return;
/* Remove it from its current bin. */
unlink_segment(area, segment_map);
/* Push it onto the front of its new bin. */
segment_index = get_segment_index(area, segment_map);
segment_map->header->prev = DSA_SEGMENT_INDEX_NONE;
segment_map->header->next = area->control->segment_bins[new_bin];
segment_map->header->bin = new_bin;
area->control->segment_bins[new_bin] = segment_index; if (segment_map->header->next != DSA_SEGMENT_INDEX_NONE)
{
dsa_segment_map *next;
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.