diff --git a/src/ivfbuild.c b/src/ivfbuild.c
index c51f40884..4665a5ff7 100644
--- a/src/ivfbuild.c
+++ b/src/ivfbuild.c
@@ -19,6 +19,7 @@
 #include "tcop/tcopprot.h"
 #include "utils/memutils.h"
 #include "vector.h"
+#include <math.h>
 
 #if PG_VERSION_NUM >= 140000
 #include "utils/backend_progress.h"
@@ -31,22 +32,22 @@
 #include "utils/wait_event.h"
 #endif
 
-#define PARALLEL_KEY_IVFFLAT_SHARED		UINT64CONST(0xA000000000000001)
-#define PARALLEL_KEY_TUPLESORT			UINT64CONST(0xA000000000000002)
-#define PARALLEL_KEY_IVFFLAT_CENTERS	UINT64CONST(0xA000000000000003)
-#define PARALLEL_KEY_QUERY_TEXT			UINT64CONST(0xA000000000000004)
+#define PARALLEL_KEY_IVFFLAT_SHARED UINT64CONST(0xA000000000000001)
+#define PARALLEL_KEY_TUPLESORT UINT64CONST(0xA000000000000002)
+#define PARALLEL_KEY_IVFFLAT_CENTERS UINT64CONST(0xA000000000000003)
+#define PARALLEL_KEY_QUERY_TEXT UINT64CONST(0xA000000000000004)
 
 /*
  * Add sample
  */
 static void
-AddSample(Datum *values, IvfflatBuildState * buildstate)
+AddSample(Datum *values, IvfflatBuildState *buildstate)
 {
 	VectorArray samples = buildstate->samples;
-	int			targsamples = samples->maxlen;
+	int targsamples = samples->maxlen;
 
 	/* Detoast once for all calls */
-	Datum		value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
+	Datum value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
 
 	/*
 	 * Normalize with KMEANS_NORM_PROC since spherical distance function
@@ -73,9 +74,9 @@ AddSample(Datum *values, IvfflatBuildState * buildstate)
 		if (buildstate->rowstoskip <= 0)
 		{
 #if PG_VERSION_NUM >= 150000
-			int			k = (int) (targsamples * sampler_random_fract(&buildstate->rstate.randstate));
+			int k = (int)(targsamples * sampler_random_fract(&buildstate->rstate.randstate));
 #else
-			int			k = (int) (targsamples * sampler_random_fract(buildstate->rstate.randstate));
+			int k = (int)(targsamples * sampler_random_fract(buildstate->rstate.randstate));
 #endif
 
 			Assert(k >= 0 && k < targsamples);
@@ -93,7 +94,7 @@ static void
 SampleCallback(Relation index, ItemPointer tid, Datum *values,
 			   bool *isnull, bool tupleIsAlive, void *state)
 {
-	IvfflatBuildState *buildstate = (IvfflatBuildState *) state;
+	IvfflatBuildState *buildstate = (IvfflatBuildState *)state;
 	MemoryContext oldCtx;
 
 	/* Skip nulls */
@@ -115,9 +116,9 @@ SampleCallback(Relation index, ItemPointer tid, Datum *values,
  * Sample rows with same logic as ANALYZE
  */
 static void
-SampleRows(IvfflatBuildState * buildstate)
+SampleRows(IvfflatBuildState *buildstate)
 {
-	int			targsamples = buildstate->samples->maxlen;
+	int targsamples = buildstate->samples->maxlen;
 	BlockNumber totalblocks = RelationGetNumberOfBlocks(buildstate->heap);
 
 	buildstate->rowstoskip = -1;
@@ -130,7 +131,7 @@ SampleRows(IvfflatBuildState * buildstate)
 		BlockNumber targblock = BlockSampler_Next(&buildstate->bs);
 
 		table_index_build_range_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
-									 false, true, false, targblock, 1, SampleCallback, (void *) buildstate, NULL);
+									 false, true, false, targblock, 1, SampleCallback, (void *)buildstate, NULL);
 	}
 }
 
@@ -138,16 +139,16 @@ SampleRows(IvfflatBuildState * buildstate)
  * Add tuple to sort
  */
 static void
-AddTupleToSort(Relation index, ItemPointer tid, Datum *values, IvfflatBuildState * buildstate)
+AddTupleToSort(Relation index, ItemPointer tid, Datum *values, IvfflatBuildState *buildstate)
 {
-	double		distance;
-	double		minDistance = DBL_MAX;
-	int			closestCenter = 0;
+	double distance;
+	double minDistance = DBL_MAX;
+	int closestCenter = 0;
 	VectorArray centers = buildstate->centers;
 	TupleTableSlot *slot = buildstate->slot;
 
 	/* Detoast once for all calls */
-	Datum		value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
+	Datum value = PointerGetDatum(PG_DETOAST_DATUM(values[0]));
 
 	/* Normalize if needed */
 	if (buildstate->normprocinfo != NULL)
@@ -204,7 +205,7 @@ static void
 BuildCallback(Relation index, ItemPointer tid, Datum *values,
 			  bool *isnull, bool tupleIsAlive, void *state)
 {
-	IvfflatBuildState *buildstate = (IvfflatBuildState *) state;
+	IvfflatBuildState *buildstate = (IvfflatBuildState *)state;
 	MemoryContext oldCtx;
 
 	/* Skip nulls */
@@ -225,20 +226,21 @@ BuildCallback(Relation index, ItemPointer tid, Datum *values,
 /*
  * Get index tuple from sort state
  */
+
 static inline void
 GetNextTuple(Tuplesortstate *sortstate, TupleDesc tupdesc, TupleTableSlot *slot, IndexTuple *itup, int *list)
 {
 	if (tuplesort_gettupleslot(sortstate, true, false, slot, NULL))
 	{
-		Datum		value;
-		bool		isnull;
+		Datum value;
+		bool isnull;
 
 		*list = DatumGetInt32(slot_getattr(slot, 1, &isnull));
 		value = slot_getattr(slot, 3, &isnull);
 
 		/* Form the index tuple */
 		*itup = index_form_tuple(tupdesc, &value, &isnull);
-		(*itup)->t_tid = *((ItemPointer) DatumGetPointer(slot_getattr(slot, 2, &isnull)));
+		(*itup)->t_tid = *((ItemPointer)DatumGetPointer(slot_getattr(slot, 2, &isnull)));
 	}
 	else
 		*list = -1;
@@ -247,15 +249,22 @@ GetNextTuple(Tuplesortstate *sortstate, TupleDesc tupdesc, TupleTableSlot *slot,
 /*
  * Create initial entry pages
  */
+
+typedef struct MetaBlockData
+{
+	int count;
+	BlockNumber blocknos[FLEXIBLE_ARRAY_MEMBER]; // Flexible array member
+} MetaBlockData;
+
 static void
-InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
+InsertTuples(Relation index, IvfflatBuildState *buildstate, ForkNumber forkNum)
 {
-	int			list;
-	IndexTuple	itup = NULL;	/* silence compiler warning */
-	int64		inserted = 0;
+	int list;
+	IndexTuple itup = NULL;
+	int64 inserted = 0;
 
 	TupleTableSlot *slot = MakeSingleTupleTableSlot(buildstate->sortdesc, &TTSOpsMinimalTuple);
-	TupleDesc	tupdesc = buildstate->tupdesc;
+	TupleDesc tupdesc = buildstate->tupdesc;
 
 	pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_LOAD);
 
@@ -265,32 +274,33 @@ InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
 
 	for (int i = 0; i < buildstate->centers->length; i++)
 	{
-		Buffer		buf;
-		Page		page;
+		Buffer buf;
+		Page page;
 		GenericXLogState *state;
 		BlockNumber startPage;
 		BlockNumber insertPage;
+		List *dataBlockList = NIL;
 
-		/* Can take a while, so ensure we can interrupt */
-		/* Needs to be called when no buffer locks are held */
 		CHECK_FOR_INTERRUPTS();
 
 		buf = IvfflatNewBuffer(index, forkNum);
 		IvfflatInitRegisterPage(index, &buf, &page, &state);
 
 		startPage = BufferGetBlockNumber(buf);
+		// For each cluster centroid, keep a list that contains all the block numbers of the pages containing embeddings for that centroid
+		dataBlockList = lappend_int(dataBlockList, startPage);
 
-		/* Get all tuples for list */
 		while (list == i)
 		{
-			/* Check for free space */
-			Size		itemsz = MAXALIGN(IndexTupleSize(itup));
+			Size itemsz = MAXALIGN(IndexTupleSize(itup));
 
 			if (PageGetFreeSpace(page) < itemsz)
+			{
 				IvfflatAppendPage(index, &buf, &page, &state, forkNum);
+				dataBlockList = lappend_int(dataBlockList, BufferGetBlockNumber(buf));
+			}
 
-			/* Add the item */
-			if (PageAddItem(page, (Item) itup, itemsz, InvalidOffsetNumber, false, false) == InvalidOffsetNumber)
+			if (PageAddItem(page, (Item)itup, itemsz, InvalidOffsetNumber, false, false) == InvalidOffsetNumber)
 				elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
 
 			pfree(itup);
@@ -301,11 +311,68 @@ InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
 		}
 
 		insertPage = BufferGetBlockNumber(buf);
-
 		IvfflatCommitBuffer(buf, state);
 
-		/* Set the start and insert pages */
-		IvfflatUpdateList(index, buildstate->listInfo[i], insertPage, InvalidBlockNumber, startPage, forkNum);
+		Buffer metabuf;
+		Page metapage;
+		GenericXLogState *metastate;
+		BlockNumber startMetaPage;
+
+		CHECK_FOR_INTERRUPTS();
+
+		metabuf = IvfflatNewBuffer(index, forkNum);
+		metastate = GenericXLogStart(index);
+		metapage = GenericXLogRegisterBuffer(metastate, metabuf, GENERIC_XLOG_FULL_IMAGE);
+		IvfflatInitPage(metabuf, metapage); // make sure page is zeroed
+
+		startMetaPage = BufferGetBlockNumber(metabuf);
+		int numBlocks = list_length(dataBlockList);
+
+		int total_block_ids_added = 0;
+
+		int max_blocks_per_page = (PageGetFreeSpace(metapage) - MAXALIGN(sizeof(struct MetaBlockData))) / sizeof(BlockNumber);
+
+		// For each cluster centroid, generate a list of metapages, each one containing a part of the block list.
+		// During query execution time, we can need to scan this metapages chain in order to retrieve the block list.
+		while (list_length(dataBlockList) > 0)
+		{
+			int total_count = Min(max_blocks_per_page, list_length(dataBlockList));
+			Size item_size = offsetof(MetaBlockData, blocknos) + sizeof(BlockNumber) * total_count;
+			MetaBlockData *metaDataItem = (MetaBlockData *)palloc0(item_size);
+			metaDataItem->count = total_count;
+			int added_items = 0;
+
+			for (int i = 0; i < total_count; i++)
+			{
+				BlockNumber blkno = linitial_int(dataBlockList);
+				metaDataItem->blocknos[i] = blkno;
+				dataBlockList = list_delete_first(dataBlockList);
+			}
+
+			total_block_ids_added += total_count;
+
+			if (PageGetFreeSpace(metapage) < item_size)
+			{
+				elog(ERROR, "FAILED TO ADD ITEM IN PAGE, PageGetFreeSpace(metapage)=%ld", PageGetFreeSpace(metapage));
+			}
+
+			if (PageAddItem(metapage, (Item)metaDataItem, item_size, InvalidOffsetNumber, false, false) == InvalidOffsetNumber)
+				elog(ERROR, "failed to add metadata item, item size=%ld, PageGetFreeSpace(metapage)=%ld", item_size, PageGetFreeSpace(metapage));
+
+			if (list_length(dataBlockList) > 0)
+			{
+				// We need to append more items, create a new metapage
+				IvfflatAppendPage(index, &metabuf, &metapage, &metastate, forkNum);
+				IvfflatInitPage(metabuf, metapage);
+			}
+
+			pfree(metaDataItem);
+		}
+
+		IvfflatCommitBuffer(metabuf, metastate);
+		IvfflatUpdateList(index, buildstate->listInfo[i], insertPage, InvalidBlockNumber, startMetaPage, numBlocks, forkNum);
+
+		list_free(dataBlockList);
 	}
 }
 
@@ -313,7 +380,7 @@ InsertTuples(Relation index, IvfflatBuildState * buildstate, ForkNumber forkNum)
  * Initialize the build state
  */
 static void
-InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, IndexInfo *indexInfo)
+InitBuildState(IvfflatBuildState *buildstate, Relation heap, Relation index, IndexInfo *indexInfo)
 {
 	buildstate->heap = heap;
 	buildstate->index = index;
@@ -358,9 +425,9 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
 
 	/* Create tuple description for sorting */
 	buildstate->sortdesc = CreateTemplateTupleDesc(3);
-	TupleDescInitEntry(buildstate->sortdesc, (AttrNumber) 1, "list", INT4OID, -1, 0);
-	TupleDescInitEntry(buildstate->sortdesc, (AttrNumber) 2, "tid", TIDOID, -1, 0);
-	TupleDescInitEntry(buildstate->sortdesc, (AttrNumber) 3, "vector", TupleDescAttr(buildstate->tupdesc, 0)->atttypid, -1, 0);
+	TupleDescInitEntry(buildstate->sortdesc, (AttrNumber)1, "list", INT4OID, -1, 0);
+	TupleDescInitEntry(buildstate->sortdesc, (AttrNumber)2, "tid", TIDOID, -1, 0);
+	TupleDescInitEntry(buildstate->sortdesc, (AttrNumber)3, "vector", TupleDescAttr(buildstate->tupdesc, 0)->atttypid, -1, 0);
 
 	buildstate->slot = MakeSingleTupleTableSlot(buildstate->sortdesc, &TTSOpsVirtual);
 
@@ -384,7 +451,7 @@ InitBuildState(IvfflatBuildState * buildstate, Relation heap, Relation index, In
  * Free resources
  */
 static void
-FreeBuildState(IvfflatBuildState * buildstate)
+FreeBuildState(IvfflatBuildState *buildstate)
 {
 	VectorArrayFree(buildstate->centers);
 	pfree(buildstate->listInfo);
@@ -401,9 +468,9 @@ FreeBuildState(IvfflatBuildState * buildstate)
  * Compute centers
  */
 static void
-ComputeCenters(IvfflatBuildState * buildstate)
+ComputeCenters(IvfflatBuildState *buildstate)
 {
-	int			numSamples;
+	int numSamples;
 
 	pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_KMEANS);
 
@@ -446,8 +513,8 @@ ComputeCenters(IvfflatBuildState * buildstate)
 static void
 CreateMetaPage(Relation index, int dimensions, int lists, ForkNumber forkNum)
 {
-	Buffer		buf;
-	Page		page;
+	Buffer buf;
+	Page page;
 	GenericXLogState *state;
 	IvfflatMetaPage metap;
 
@@ -460,8 +527,8 @@ CreateMetaPage(Relation index, int dimensions, int lists, ForkNumber forkNum)
 	metap->version = IVFFLAT_VERSION;
 	metap->dimensions = dimensions;
 	metap->lists = lists;
-	((PageHeader) page)->pd_lower =
-		((char *) metap + sizeof(IvfflatMetaPageData)) - (char *) page;
+	((PageHeader)page)->pd_lower =
+		((char *)metap + sizeof(IvfflatMetaPageData)) - (char *)page;
 
 	IvfflatCommitBuffer(buf, state);
 }
@@ -470,13 +537,12 @@ CreateMetaPage(Relation index, int dimensions, int lists, ForkNumber forkNum)
  * Create list pages
  */
 static void
-CreateListPages(Relation index, VectorArray centers, int dimensions,
-				int lists, ForkNumber forkNum, ListInfo * *listInfo)
+CreateListPages(Relation index, VectorArray centers, int dimensions, int lists, ForkNumber forkNum, ListInfo **listInfo)
 {
-	Buffer		buf;
-	Page		page;
+	Buffer buf;
+	Page page;
 	GenericXLogState *state;
-	Size		listSize;
+	Size listSize;
 	IvfflatList list;
 
 	listSize = MAXALIGN(IVFFLAT_LIST_SIZE(centers->itemsize));
@@ -495,6 +561,7 @@ CreateListPages(Relation index, VectorArray centers, int dimensions,
 		/* Load list */
 		list->startPage = InvalidBlockNumber;
 		list->insertPage = InvalidBlockNumber;
+		list->numBlocks = 0;
 		memcpy(&list->center, VectorArrayGet(centers, i), VARSIZE_ANY(VectorArrayGet(centers, i)));
 
 		/* Ensure free space */
@@ -502,7 +569,7 @@ CreateListPages(Relation index, VectorArray centers, int dimensions,
 			IvfflatAppendPage(index, &buf, &page, &state, forkNum);
 
 		/* Add the item */
-		offno = PageAddItem(page, (Item) list, listSize, InvalidOffsetNumber, false, false);
+		offno = PageAddItem(page, (Item)list, listSize, InvalidOffsetNumber, false, false);
 		if (offno == InvalidOffsetNumber)
 			elog(ERROR, "failed to add index item to \"%s\"", RelationGetRelationName(index));
 
@@ -521,14 +588,14 @@ CreateListPages(Relation index, VectorArray centers, int dimensions,
  * Print k-means metrics
  */
 static void
-PrintKmeansMetrics(IvfflatBuildState * buildstate)
+PrintKmeansMetrics(IvfflatBuildState *buildstate)
 {
 	elog(INFO, "inertia: %.3e", buildstate->inertia);
 
 	/* Calculate Davies-Bouldin index */
 	if (buildstate->lists > 1 && !buildstate->ivfleader)
 	{
-		double		db = 0.0;
+		double db = 0.0;
 
 		/* Calculate average distance */
 		for (int i = 0; i < buildstate->lists; i++)
@@ -539,8 +606,8 @@ PrintKmeansMetrics(IvfflatBuildState * buildstate)
 
 		for (int i = 0; i < buildstate->lists; i++)
 		{
-			double		max = 0.0;
-			double		distance;
+			double max = 0.0;
+			double distance;
 
 			for (int j = 0; j < buildstate->lists; j++)
 			{
@@ -567,10 +634,10 @@ PrintKmeansMetrics(IvfflatBuildState * buildstate)
 static Tuplesortstate *
 InitBuildSortState(TupleDesc tupdesc, int memory, SortCoordinate coordinate)
 {
-	AttrNumber	attNums[] = {1};
-	Oid			sortOperators[] = {Int4LessOperator};
-	Oid			sortCollations[] = {InvalidOid};
-	bool		nullsFirstFlags[] = {false};
+	AttrNumber attNums[] = {1};
+	Oid sortOperators[] = {Int4LessOperator};
+	Oid sortCollations[] = {InvalidOid};
+	bool nullsFirstFlags[] = {false};
 
 	return tuplesort_begin_heap(tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, memory, coordinate, false);
 }
@@ -579,11 +646,11 @@ InitBuildSortState(TupleDesc tupdesc, int memory, SortCoordinate coordinate)
  * Within leader, wait for end of heap scan
  */
 static double
-ParallelHeapScan(IvfflatBuildState * buildstate)
+ParallelHeapScan(IvfflatBuildState *buildstate)
 {
 	IvfflatShared *ivfshared = buildstate->ivfleader->ivfshared;
-	int			nparticipanttuplesorts;
-	double		reltuples;
+	int nparticipanttuplesorts;
+	double reltuples;
 
 	nparticipanttuplesorts = buildstate->ivfleader->nparticipanttuplesorts;
 	for (;;)
@@ -614,13 +681,13 @@ ParallelHeapScan(IvfflatBuildState * buildstate)
  * Perform a worker's portion of a parallel sort
  */
 static void
-IvfflatParallelScanAndSort(IvfflatSpool * ivfspool, IvfflatShared * ivfshared, Sharedsort *sharedsort, char *ivfcenters, int sortmem, bool progress)
+IvfflatParallelScanAndSort(IvfflatSpool *ivfspool, IvfflatShared *ivfshared, Sharedsort *sharedsort, char *ivfcenters, int sortmem, bool progress)
 {
 	SortCoordinate coordinate;
 	IvfflatBuildState buildstate;
 	TableScanDesc scan;
-	double		reltuples;
-	IndexInfo  *indexInfo;
+	double reltuples;
+	IndexInfo *indexInfo;
 
 	/* Initialize local tuplesort coordination state */
 	coordinate = palloc0(sizeof(SortCoordinateData));
@@ -640,7 +707,7 @@ IvfflatParallelScanAndSort(IvfflatSpool * ivfspool, IvfflatShared * ivfshared, S
 									ParallelTableScanFromIvfflatShared(ivfshared));
 	reltuples = table_index_build_scan(ivfspool->heap, ivfspool->index, indexInfo,
 									   true, progress, BuildCallback,
-									   (void *) &buildstate, scan);
+									   (void *)&buildstate, scan);
 
 	/* Execute this worker's part of the sort */
 	tuplesort_performsort(ivfspool->sortstate);
@@ -657,9 +724,9 @@ IvfflatParallelScanAndSort(IvfflatSpool * ivfspool, IvfflatShared * ivfshared, S
 
 	/* Log statistics */
 	if (progress)
-		ereport(DEBUG1, (errmsg("leader processed " INT64_FORMAT " tuples", (int64) reltuples)));
+		ereport(DEBUG1, (errmsg("leader processed " INT64_FORMAT " tuples", (int64)reltuples)));
 	else
-		ereport(DEBUG1, (errmsg("worker processed " INT64_FORMAT " tuples", (int64) reltuples)));
+		ereport(DEBUG1, (errmsg("worker processed " INT64_FORMAT " tuples", (int64)reltuples)));
 
 	/* Notify leader */
 	ConditionVariableSignal(&ivfshared->workersdonecv);
@@ -673,19 +740,18 @@ IvfflatParallelScanAndSort(IvfflatSpool * ivfspool, IvfflatShared * ivfshared, S
 /*
  * Perform work within a launched parallel process
  */
-void
-IvfflatParallelBuildMain(dsm_segment *seg, shm_toc *toc)
+void IvfflatParallelBuildMain(dsm_segment *seg, shm_toc *toc)
 {
-	char	   *sharedquery;
+	char *sharedquery;
 	IvfflatSpool *ivfspool;
 	IvfflatShared *ivfshared;
 	Sharedsort *sharedsort;
-	char	   *ivfcenters;
-	Relation	heapRel;
-	Relation	indexRel;
-	LOCKMODE	heapLockmode;
-	LOCKMODE	indexLockmode;
-	int			sortmem;
+	char *ivfcenters;
+	Relation heapRel;
+	Relation indexRel;
+	LOCKMODE heapLockmode;
+	LOCKMODE indexLockmode;
+	int sortmem;
 
 	/* Set debug_query_string for individual workers first */
 	sharedquery = shm_toc_lookup(toc, PARALLEL_KEY_QUERY_TEXT, true);
@@ -714,7 +780,7 @@ IvfflatParallelBuildMain(dsm_segment *seg, shm_toc *toc)
 	indexRel = index_open(ivfshared->indexrelid, indexLockmode);
 
 	/* Initialize worker's own spool */
-	ivfspool = (IvfflatSpool *) palloc0(sizeof(IvfflatSpool));
+	ivfspool = (IvfflatSpool *)palloc0(sizeof(IvfflatSpool));
 	ivfspool->heap = heapRel;
 	ivfspool->index = indexRel;
 
@@ -737,7 +803,7 @@ IvfflatParallelBuildMain(dsm_segment *seg, shm_toc *toc)
  * End parallel build
  */
 static void
-IvfflatEndParallel(IvfflatLeader * ivfleader)
+IvfflatEndParallel(IvfflatLeader *ivfleader)
 {
 	/* Shutdown worker processes */
 	WaitForParallelWorkersToFinish(ivfleader->pcxt);
@@ -762,14 +828,14 @@ ParallelEstimateShared(Relation heap, Snapshot snapshot)
  * Within leader, participate as a parallel worker
  */
 static void
-IvfflatLeaderParticipateAsWorker(IvfflatBuildState * buildstate)
+IvfflatLeaderParticipateAsWorker(IvfflatBuildState *buildstate)
 {
 	IvfflatLeader *ivfleader = buildstate->ivfleader;
 	IvfflatSpool *leaderworker;
-	int			sortmem;
+	int sortmem;
 
 	/* Allocate memory and initialize private spool */
-	leaderworker = (IvfflatSpool *) palloc0(sizeof(IvfflatSpool));
+	leaderworker = (IvfflatSpool *)palloc0(sizeof(IvfflatSpool));
 	leaderworker->heap = buildstate->heap;
 	leaderworker->index = buildstate->index;
 
@@ -784,20 +850,20 @@ IvfflatLeaderParticipateAsWorker(IvfflatBuildState * buildstate)
  * Begin parallel build
  */
 static void
-IvfflatBeginParallel(IvfflatBuildState * buildstate, bool isconcurrent, int request)
+IvfflatBeginParallel(IvfflatBuildState *buildstate, bool isconcurrent, int request)
 {
 	ParallelContext *pcxt;
-	int			scantuplesortstates;
-	Snapshot	snapshot;
-	Size		estivfshared;
-	Size		estsort;
-	Size		estcenters;
+	int scantuplesortstates;
+	Snapshot snapshot;
+	Size estivfshared;
+	Size estsort;
+	Size estcenters;
 	IvfflatShared *ivfshared;
 	Sharedsort *sharedsort;
-	char	   *ivfcenters;
-	IvfflatLeader *ivfleader = (IvfflatLeader *) palloc0(sizeof(IvfflatLeader));
-	bool		leaderparticipates = true;
-	int			querylen;
+	char *ivfcenters;
+	IvfflatLeader *ivfleader = (IvfflatLeader *)palloc0(sizeof(IvfflatLeader));
+	bool leaderparticipates = true;
+	int querylen;
 
 #ifdef DISABLE_LEADER_PARTICIPATION
 	leaderparticipates = false;
@@ -833,7 +899,7 @@ IvfflatBeginParallel(IvfflatBuildState * buildstate, bool isconcurrent, int requ
 		shm_toc_estimate_keys(&pcxt->estimator, 1);
 	}
 	else
-		querylen = 0;			/* keep compiler quiet */
+		querylen = 0; /* keep compiler quiet */
 
 	/* Everyone's had a chance to ask for space, so now create the DSM */
 	InitializeParallelDSM(pcxt);
@@ -849,7 +915,7 @@ IvfflatBeginParallel(IvfflatBuildState * buildstate, bool isconcurrent, int requ
 	}
 
 	/* Store shared build state, for which we reserved space */
-	ivfshared = (IvfflatShared *) shm_toc_allocate(pcxt->toc, estivfshared);
+	ivfshared = (IvfflatShared *)shm_toc_allocate(pcxt->toc, estivfshared);
 	/* Initialize immutable state */
 	ivfshared->heaprelid = RelationGetRelid(buildstate->heap);
 	ivfshared->indexrelid = RelationGetRelid(buildstate->index);
@@ -869,7 +935,7 @@ IvfflatBeginParallel(IvfflatBuildState * buildstate, bool isconcurrent, int requ
 								  snapshot);
 
 	/* Store shared tuplesort-private state, for which we reserved space */
-	sharedsort = (Sharedsort *) shm_toc_allocate(pcxt->toc, estsort);
+	sharedsort = (Sharedsort *)shm_toc_allocate(pcxt->toc, estsort);
 	tuplesort_initialize_shared(sharedsort, scantuplesortstates,
 								pcxt->seg);
 
@@ -883,9 +949,9 @@ IvfflatBeginParallel(IvfflatBuildState * buildstate, bool isconcurrent, int requ
 	/* Store query string for workers */
 	if (debug_query_string)
 	{
-		char	   *sharedquery;
+		char *sharedquery;
 
-		sharedquery = (char *) shm_toc_allocate(pcxt->toc, querylen + 1);
+		sharedquery = (char *)shm_toc_allocate(pcxt->toc, querylen + 1);
 		memcpy(sharedquery, debug_query_string, querylen + 1);
 		shm_toc_insert(pcxt->toc, PARALLEL_KEY_QUERY_TEXT, sharedquery);
 	}
@@ -926,9 +992,9 @@ IvfflatBeginParallel(IvfflatBuildState * buildstate, bool isconcurrent, int requ
  * Scan table for tuples to index
  */
 static void
-AssignTuples(IvfflatBuildState * buildstate)
+AssignTuples(IvfflatBuildState *buildstate)
 {
-	int			parallel_workers = 0;
+	int parallel_workers = 0;
 	SortCoordinate coordinate = NULL;
 
 	pgstat_progress_update_param(PROGRESS_CREATEIDX_SUBPHASE, PROGRESS_IVFFLAT_PHASE_ASSIGN);
@@ -944,7 +1010,7 @@ AssignTuples(IvfflatBuildState * buildstate)
 	/* Set up coordination state if at least one worker launched */
 	if (buildstate->ivfleader)
 	{
-		coordinate = (SortCoordinate) palloc0(sizeof(SortCoordinateData));
+		coordinate = (SortCoordinate)palloc0(sizeof(SortCoordinateData));
 		coordinate->isWorker = false;
 		coordinate->nParticipants = buildstate->ivfleader->nparticipanttuplesorts;
 		coordinate->sharedsort = buildstate->ivfleader->sharedsort;
@@ -960,7 +1026,7 @@ AssignTuples(IvfflatBuildState * buildstate)
 			buildstate->reltuples = ParallelHeapScan(buildstate);
 		else
 			buildstate->reltuples = table_index_build_scan(buildstate->heap, buildstate->index, buildstate->indexInfo,
-														   true, true, BuildCallback, (void *) buildstate, NULL);
+														   true, true, BuildCallback, (void *)buildstate, NULL);
 
 #ifdef IVFFLAT_KMEANS_DEBUG
 		PrintKmeansMetrics(buildstate);
@@ -972,7 +1038,7 @@ AssignTuples(IvfflatBuildState * buildstate)
  * Create entry pages
  */
 static void
-CreateEntryPages(IvfflatBuildState * buildstate, ForkNumber forkNum)
+CreateEntryPages(IvfflatBuildState *buildstate, ForkNumber forkNum)
 {
 	/* Assign */
 	IvfflatBench("assign tuples", AssignTuples(buildstate));
@@ -996,7 +1062,7 @@ CreateEntryPages(IvfflatBuildState * buildstate, ForkNumber forkNum)
  */
 static void
 BuildIndex(Relation heap, Relation index, IndexInfo *indexInfo,
-		   IvfflatBuildState * buildstate, ForkNumber forkNum)
+		   IvfflatBuildState *buildstate, ForkNumber forkNum)
 {
 	InitBuildState(buildstate, heap, index, indexInfo);
 
@@ -1023,13 +1089,9 @@ ivfflatbuild(Relation heap, Relation index, IndexInfo *indexInfo)
 	IndexBuildResult *result;
 	IvfflatBuildState buildstate;
 
-#ifdef IVFFLAT_BENCH
-	SeedRandom(42);
-#endif
-
 	BuildIndex(heap, index, indexInfo, &buildstate, MAIN_FORKNUM);
 
-	result = (IndexBuildResult *) palloc(sizeof(IndexBuildResult));
+	result = (IndexBuildResult *)palloc(sizeof(IndexBuildResult));
 	result->heap_tuples = buildstate.reltuples;
 	result->index_tuples = buildstate.indtuples;
 
@@ -1039,10 +1101,9 @@ ivfflatbuild(Relation heap, Relation index, IndexInfo *indexInfo)
 /*
  * Build the index for an unlogged table
  */
-void
-ivfflatbuildempty(Relation index)
+void ivfflatbuildempty(Relation index)
 {
-	IndexInfo  *indexInfo = BuildIndexInfo(index);
+	IndexInfo *indexInfo = BuildIndexInfo(index);
 	IvfflatBuildState buildstate;
 
 	BuildIndex(NULL, index, indexInfo, &buildstate, INIT_FORKNUM);
diff --git a/src/ivfflat.h b/src/ivfflat.h
index 76608f334..417ec2f49 100644
--- a/src/ivfflat.h
+++ b/src/ivfflat.h
@@ -8,7 +8,7 @@
 #include "access/parallel.h"
 #include "lib/pairingheap.h"
 #include "nodes/execnodes.h"
-#include "port.h"				/* for random() */
+#include "port.h" /* for random() */
 #include "utils/sampling.h"
 #include "utils/tuplesort.h"
 #include "vector.h"
@@ -30,40 +30,41 @@
 #define IVFFLAT_KMEANS_NORM_PROC 4
 #define IVFFLAT_TYPE_INFO_PROC 5
 
-#define IVFFLAT_VERSION	1
+#define IVFFLAT_VERSION 1
 #define IVFFLAT_MAGIC_NUMBER 0x14FF1A7
-#define IVFFLAT_PAGE_ID	0xFF84
+#define IVFFLAT_PAGE_ID 0xFF84
 
 /* Preserved page numbers */
-#define IVFFLAT_METAPAGE_BLKNO	0
-#define IVFFLAT_HEAD_BLKNO		1	/* first list page */
+#define IVFFLAT_METAPAGE_BLKNO 0
+#define IVFFLAT_HEAD_BLKNO 1 /* first list page */
 
 /* IVFFlat parameters */
-#define IVFFLAT_DEFAULT_LISTS	100
-#define IVFFLAT_MIN_LISTS		1
-#define IVFFLAT_MAX_LISTS		32768
-#define IVFFLAT_DEFAULT_PROBES	1
+#define IVFFLAT_DEFAULT_LISTS 100
+#define IVFFLAT_MIN_LISTS 1
+#define IVFFLAT_MAX_LISTS 32768
+#define IVFFLAT_DEFAULT_PROBES 1
 
 /* Build phases */
 /* PROGRESS_CREATEIDX_SUBPHASE_INITIALIZE is 1 */
-#define PROGRESS_IVFFLAT_PHASE_KMEANS	2
-#define PROGRESS_IVFFLAT_PHASE_ASSIGN	3
-#define PROGRESS_IVFFLAT_PHASE_LOAD		4
+#define PROGRESS_IVFFLAT_PHASE_KMEANS 2
+#define PROGRESS_IVFFLAT_PHASE_ASSIGN 3
+#define PROGRESS_IVFFLAT_PHASE_LOAD 4
 
-#define IVFFLAT_LIST_SIZE(size)	(offsetof(IvfflatListData, center) + size)
+#define IVFFLAT_LIST_SIZE(size) (offsetof(IvfflatListData, center) + size)
 
-#define IvfflatPageGetOpaque(page)	((IvfflatPageOpaque) PageGetSpecialPointer(page))
-#define IvfflatPageGetMeta(page)	((IvfflatMetaPageData *) PageGetContents(page))
+#define IvfflatPageGetOpaque(page) ((IvfflatPageOpaque)PageGetSpecialPointer(page))
+#define IvfflatPageGetMeta(page) ((IvfflatMetaPageData *)PageGetContents(page))
 
 #ifdef IVFFLAT_BENCH
-#define IvfflatBench(name, code) \
-	do { \
-		instr_time	start; \
-		instr_time	duration; \
-		INSTR_TIME_SET_CURRENT(start); \
-		(code); \
-		INSTR_TIME_SET_CURRENT(duration); \
-		INSTR_TIME_SUBTRACT(duration, start); \
+#define IvfflatBench(name, code)                                            \
+	do                                                                      \
+	{                                                                       \
+		instr_time start;                                                   \
+		instr_time duration;                                                \
+		INSTR_TIME_SET_CURRENT(start);                                      \
+		(code);                                                             \
+		INSTR_TIME_SET_CURRENT(duration);                                   \
+		INSTR_TIME_SUBTRACT(duration, start);                               \
 		elog(INFO, "%s: %.3f ms", name, INSTR_TIME_GET_MILLISEC(duration)); \
 	} while (0)
 #else
@@ -73,143 +74,141 @@
 #if PG_VERSION_NUM >= 150000
 #define RandomDouble() pg_prng_double(&pg_global_prng_state)
 #define RandomInt() pg_prng_uint32(&pg_global_prng_state)
-#define SeedRandom(seed) pg_prng_seed(&pg_global_prng_state, seed)
 #else
-#define RandomDouble() (((double) random()) / MAX_RANDOM_VALUE)
+#define RandomDouble() (((double)random()) / MAX_RANDOM_VALUE)
 #define RandomInt() random()
-#define SeedRandom(seed) srandom(seed)
 #endif
 
 /* Variables */
-extern int	ivfflat_probes;
-extern int	ivfflat_iterative_scan;
-extern int	ivfflat_max_probes;
+extern int ivfflat_probes;
+extern int ivfflat_iterative_scan;
+extern int ivfflat_max_probes;
 
 typedef enum IvfflatIterativeScanMode
 {
 	IVFFLAT_ITERATIVE_SCAN_OFF,
 	IVFFLAT_ITERATIVE_SCAN_RELAXED
-}			IvfflatIterativeScanMode;
+} IvfflatIterativeScanMode;
 
 typedef struct VectorArrayData
 {
-	int			length;
-	int			maxlen;
-	int			dim;
-	Size		itemsize;
-	char	   *items;
-}			VectorArrayData;
+	int length;
+	int maxlen;
+	int dim;
+	Size itemsize;
+	char *items;
+} VectorArrayData;
 
-typedef VectorArrayData * VectorArray;
+typedef VectorArrayData *VectorArray;
 
 typedef struct ListInfo
 {
 	BlockNumber blkno;
 	OffsetNumber offno;
-}			ListInfo;
+} ListInfo;
 
 /* IVFFlat index options */
 typedef struct IvfflatOptions
 {
-	int32		vl_len_;		/* varlena header (do not touch directly!) */
-	int			lists;			/* number of lists */
-}			IvfflatOptions;
+	int32 vl_len_; /* varlena header (do not touch directly!) */
+	int lists;	   /* number of lists */
+} IvfflatOptions;
 
 typedef struct IvfflatSpool
 {
 	Tuplesortstate *sortstate;
-	Relation	heap;
-	Relation	index;
-}			IvfflatSpool;
+	Relation heap;
+	Relation index;
+} IvfflatSpool;
 
 typedef struct IvfflatShared
 {
 	/* Immutable state */
-	Oid			heaprelid;
-	Oid			indexrelid;
-	bool		isconcurrent;
-	int			scantuplesortstates;
+	Oid heaprelid;
+	Oid indexrelid;
+	bool isconcurrent;
+	int scantuplesortstates;
 
 	/* Worker progress */
 	ConditionVariable workersdonecv;
 
 	/* Mutex for mutable state */
-	slock_t		mutex;
+	slock_t mutex;
 
 	/* Mutable state */
-	int			nparticipantsdone;
-	double		reltuples;
-	double		indtuples;
+	int nparticipantsdone;
+	double reltuples;
+	double indtuples;
 
 #ifdef IVFFLAT_KMEANS_DEBUG
-	double		inertia;
+	double inertia;
 #endif
-}			IvfflatShared;
+} IvfflatShared;
 
 #define ParallelTableScanFromIvfflatShared(shared) \
-	(ParallelTableScanDesc) ((char *) (shared) + BUFFERALIGN(sizeof(IvfflatShared)))
+	(ParallelTableScanDesc)((char *)(shared) + BUFFERALIGN(sizeof(IvfflatShared)))
 
 typedef struct IvfflatLeader
 {
 	ParallelContext *pcxt;
-	int			nparticipanttuplesorts;
+	int nparticipanttuplesorts;
 	IvfflatShared *ivfshared;
 	Sharedsort *sharedsort;
-	Snapshot	snapshot;
-	char	   *ivfcenters;
-}			IvfflatLeader;
+	Snapshot snapshot;
+	char *ivfcenters;
+} IvfflatLeader;
 
 typedef struct IvfflatTypeInfo
 {
-	int			maxDimensions;
-	Datum		(*normalize) (PG_FUNCTION_ARGS);
-	Size		(*itemSize) (int dimensions);
-	void		(*updateCenter) (Pointer v, int dimensions, float *x);
-	void		(*sumCenter) (Pointer v, float *x);
-}			IvfflatTypeInfo;
+	int maxDimensions;
+	Datum (*normalize)(PG_FUNCTION_ARGS);
+	Size (*itemSize)(int dimensions);
+	void (*updateCenter)(Pointer v, int dimensions, float *x);
+	void (*sumCenter)(Pointer v, float *x);
+} IvfflatTypeInfo;
 
 typedef struct IvfflatBuildState
 {
 	/* Info */
-	Relation	heap;
-	Relation	index;
-	IndexInfo  *indexInfo;
-	const		IvfflatTypeInfo *typeInfo;
-	TupleDesc	tupdesc;
+	Relation heap;
+	Relation index;
+	IndexInfo *indexInfo;
+	const IvfflatTypeInfo *typeInfo;
+	TupleDesc tupdesc;
 
 	/* Settings */
-	int			dimensions;
-	int			lists;
+	int dimensions;
+	int lists;
 
 	/* Statistics */
-	double		indtuples;
-	double		reltuples;
+	double indtuples;
+	double reltuples;
 
 	/* Support functions */
-	FmgrInfo   *procinfo;
-	FmgrInfo   *normprocinfo;
-	FmgrInfo   *kmeansnormprocinfo;
-	Oid			collation;
+	FmgrInfo *procinfo;
+	FmgrInfo *normprocinfo;
+	FmgrInfo *kmeansnormprocinfo;
+	Oid collation;
 
 	/* Variables */
 	VectorArray samples;
 	VectorArray centers;
-	ListInfo   *listInfo;
+	ListInfo *listInfo;
 
 #ifdef IVFFLAT_KMEANS_DEBUG
-	double		inertia;
-	double	   *listSums;
-	int		   *listCounts;
+	double inertia;
+	double *listSums;
+	int *listCounts;
 #endif
 
 	/* Sampling */
 	BlockSamplerData bs;
 	ReservoirStateData rstate;
-	int			rowstoskip;
+	int rowstoskip;
 
 	/* Sorting */
 	Tuplesortstate *sortstate;
-	TupleDesc	sortdesc;
+	TupleDesc sortdesc;
 	TupleTableSlot *slot;
 
 	/* Memory */
@@ -217,74 +216,79 @@ typedef struct IvfflatBuildState
 
 	/* Parallel builds */
 	IvfflatLeader *ivfleader;
-}			IvfflatBuildState;
+} IvfflatBuildState;
 
 typedef struct IvfflatMetaPageData
 {
-	uint32		magicNumber;
-	uint32		version;
-	uint16		dimensions;
-	uint16		lists;
-}			IvfflatMetaPageData;
+	uint32 magicNumber;
+	uint32 version;
+	uint16 dimensions;
+	uint16 lists;
+} IvfflatMetaPageData;
 
-typedef IvfflatMetaPageData * IvfflatMetaPage;
+typedef IvfflatMetaPageData *IvfflatMetaPage;
 
 typedef struct IvfflatPageOpaqueData
 {
 	BlockNumber nextblkno;
-	uint16		unused;
-	uint16		page_id;		/* for identification of IVFFlat indexes */
-}			IvfflatPageOpaqueData;
+	uint16 unused;
+	uint16 page_id; /* for identification of IVFFlat indexes */
+} IvfflatPageOpaqueData;
 
-typedef IvfflatPageOpaqueData * IvfflatPageOpaque;
+typedef IvfflatPageOpaqueData *IvfflatPageOpaque;
 
 typedef struct IvfflatListData
 {
 	BlockNumber startPage;
 	BlockNumber insertPage;
-	Vector		center;
-}			IvfflatListData;
+	int numBlocks;
+	Vector center;
+} IvfflatListData;
 
-typedef IvfflatListData * IvfflatList;
+typedef IvfflatListData *IvfflatList;
 
 typedef struct IvfflatScanList
 {
 	pairingheap_node ph_node;
 	BlockNumber startPage;
-	double		distance;
-}			IvfflatScanList;
+	int numBlocks;
+	double distance;
+} IvfflatScanList;
 
 typedef struct IvfflatScanOpaqueData
 {
-	const		IvfflatTypeInfo *typeInfo;
-	int			probes;
-	int			maxProbes;
-	int			dimensions;
-	bool		first;
-	Datum		value;
+	const IvfflatTypeInfo *typeInfo;
+	int probes;
+	int maxProbes;
+	int dimensions;
+	bool first;
+	Datum value;
 	MemoryContext tmpCtx;
 
 	/* Sorting */
 	Tuplesortstate *sortstate;
-	TupleDesc	tupdesc;
+	TupleDesc tupdesc;
 	TupleTableSlot *vslot;
 	TupleTableSlot *mslot;
 	BufferAccessStrategy bas;
 
 	/* Support functions */
-	FmgrInfo   *procinfo;
-	FmgrInfo   *normprocinfo;
-	Oid			collation;
-	Datum		(*distfunc) (FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2);
+	FmgrInfo *procinfo;
+	FmgrInfo *normprocinfo;
+	Oid collation;
+	Datum (*distfunc)(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2);
 
 	/* Lists */
 	pairingheap *listQueue;
 	BlockNumber *listPages;
-	int			listIndex;
+	int listIndex;
 	IvfflatScanList *lists;
-}			IvfflatScanOpaqueData;
 
-typedef IvfflatScanOpaqueData * IvfflatScanOpaque;
+	dsm_segment *shared_dsm_segment;
+
+} IvfflatScanOpaqueData;
+
+typedef IvfflatScanOpaqueData *IvfflatScanOpaque;
 
 #define VECTOR_ARRAY_SIZE(_length, _size) (sizeof(VectorArrayData) + (_length) * MAXALIGN(_size))
 
@@ -293,7 +297,7 @@ typedef IvfflatScanOpaqueData * IvfflatScanOpaque;
 static inline Pointer
 VectorArrayGet(VectorArray arr, int offset)
 {
-	return ((char *) arr->items) + (offset * arr->itemsize);
+	return ((char *)arr->items) + (offset * arr->itemsize);
 }
 
 static inline void
@@ -304,37 +308,38 @@ VectorArraySet(VectorArray arr, int offset, Pointer val)
 
 /* Methods */
 VectorArray VectorArrayInit(int maxlen, int dimensions, Size itemsize);
-void		VectorArrayFree(VectorArray arr);
-void		IvfflatKmeans(Relation index, VectorArray samples, VectorArray centers, const IvfflatTypeInfo * typeInfo);
-FmgrInfo   *IvfflatOptionalProcInfo(Relation index, uint16 procnum);
-Datum		IvfflatNormValue(const IvfflatTypeInfo * typeInfo, Oid collation, Datum value);
-bool		IvfflatCheckNorm(FmgrInfo *procinfo, Oid collation, Datum value);
-int			IvfflatGetLists(Relation index);
-void		IvfflatGetMetaPageInfo(Relation index, int *lists, int *dimensions);
-void		IvfflatUpdateList(Relation index, ListInfo listInfo, BlockNumber insertPage, BlockNumber originalInsertPage, BlockNumber startPage, ForkNumber forkNum);
-void		IvfflatCommitBuffer(Buffer buf, GenericXLogState *state);
-void		IvfflatAppendPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state, ForkNumber forkNum);
-Buffer		IvfflatNewBuffer(Relation index, ForkNumber forkNum);
-void		IvfflatInitPage(Buffer buf, Page page);
-void		IvfflatInitRegisterPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state);
-void		IvfflatInit(void);
-const		IvfflatTypeInfo *IvfflatGetTypeInfo(Relation index);
+void VectorArrayFree(VectorArray arr);
+void IvfflatKmeans(Relation index, VectorArray samples, VectorArray centers, const IvfflatTypeInfo *typeInfo);
+FmgrInfo *IvfflatOptionalProcInfo(Relation index, uint16 procnum);
+Datum IvfflatNormValue(const IvfflatTypeInfo *typeInfo, Oid collation, Datum value);
+bool IvfflatCheckNorm(FmgrInfo *procinfo, Oid collation, Datum value);
+int IvfflatGetLists(Relation index);
+void IvfflatGetMetaPageInfo(Relation index, int *lists, int *dimensions);
+void IvfflatUpdateList(Relation index, ListInfo listInfo, BlockNumber insertPage, BlockNumber originalInsertPage, BlockNumber startPage, int numBlocks, ForkNumber forkNum);
+void IvfflatCommitBuffer(Buffer buf, GenericXLogState *state);
+void IvfflatAppendPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state, ForkNumber forkNum);
+Buffer IvfflatNewBuffer(Relation index, ForkNumber forkNum);
+void IvfflatInitPage(Buffer buf, Page page);
+void IvfflatInitRegisterPage(Relation index, Buffer *buf, Page *page, GenericXLogState **state);
+void IvfflatInit(void);
+const IvfflatTypeInfo *IvfflatGetTypeInfo(Relation index);
 PGDLLEXPORT void IvfflatParallelBuildMain(dsm_segment *seg, shm_toc *toc);
 
 /* Index access methods */
 IndexBuildResult *ivfflatbuild(Relation heap, Relation index, IndexInfo *indexInfo);
-void		ivfflatbuildempty(Relation index);
-bool		ivfflatinsert(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heap, IndexUniqueCheck checkUnique
+void ivfflatbuildempty(Relation index);
+bool ivfflatinsert(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, Relation heap, IndexUniqueCheck checkUnique
 #if PG_VERSION_NUM >= 140000
-						  ,bool indexUnchanged
+				   ,
+				   bool indexUnchanged
 #endif
-						  ,IndexInfo *indexInfo
-);
+				   ,
+				   IndexInfo *indexInfo);
 IndexBulkDeleteResult *ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state);
 IndexBulkDeleteResult *ivfflatvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats);
 IndexScanDesc ivfflatbeginscan(Relation index, int nkeys, int norderbys);
-void		ivfflatrescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys);
-bool		ivfflatgettuple(IndexScanDesc scan, ScanDirection dir);
-void		ivfflatendscan(IndexScanDesc scan);
+void ivfflatrescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys);
+bool ivfflatgettuple(IndexScanDesc scan, ScanDirection dir);
+void ivfflatendscan(IndexScanDesc scan);
 
 #endif
diff --git a/src/ivfinsert.c b/src/ivfinsert.c
index 014c9be82..21ad5a4ce 100644
--- a/src/ivfinsert.c
+++ b/src/ivfinsert.c
@@ -172,7 +172,7 @@ InsertTuple(Relation index, Datum *values, bool *isnull, ItemPointer heap_tid, R
 
 	/* Update the insert page */
 	if (insertPage != originalInsertPage)
-		IvfflatUpdateList(index, listInfo, insertPage, originalInsertPage, InvalidBlockNumber, MAIN_FORKNUM);
+		IvfflatUpdateList(index, listInfo, insertPage, originalInsertPage, InvalidBlockNumber, 0, MAIN_FORKNUM);
 }
 
 /*
diff --git a/src/ivfscan.c b/src/ivfscan.c
index 6cc5d2efd..4fda6a194 100644
--- a/src/ivfscan.c
+++ b/src/ivfscan.c
@@ -1,7 +1,13 @@
 #include "postgres.h"
 
+#include "miscadmin.h"
+#include "postmaster/bgworker.h"
+#include "storage/dsm.h"
+#include "storage/read_stream.h"
+#include "storage/bufmgr.h"
+#include "access/genam.h"
 #include <float.h>
-
+#include "nodes/pg_list.h"
 #include "access/relscan.h"
 #include "catalog/pg_operator_d.h"
 #include "catalog/pg_type_d.h"
@@ -11,10 +17,181 @@
 #include "pgstat.h"
 #include "storage/bufmgr.h"
 #include "utils/memutils.h"
+#include "portability/instr_time.h"
+#include "access/heapam.h"
+#include "catalog/index.h"
+#include <sys/mman.h>
+#include <unistd.h>
+#include "storage/procsignal.h"
+#include "postmaster/bgworker.h"
+#include "storage/ipc.h"
 
 #define GetScanList(ptr) pairingheap_container(IvfflatScanList, ph_node, ptr)
 #define GetScanListConst(ptr) pairingheap_const_container(IvfflatScanList, ph_node, ptr)
 
+extern int max_parallel_workers_per_gather;
+extern int max_worker_processes;
+
+PGDLLEXPORT void ivf_prefetch_worker_main(Datum main_arg);
+
+static HTAB *centroid_access_counts = NULL;
+static HTAB *page_hits = NULL;
+
+static int NUM_WORKERS;
+
+// The total number of workers depends on the max_worker_processes available ar runtime as well as the max_parallel_workers_per_gather knob
+void init_num_workers(void)
+{
+	NUM_WORKERS = Min(max_worker_processes, max_parallel_workers_per_gather);
+}
+
+typedef struct ResultItem
+{
+	double distance;
+	ItemPointerData tid;
+} ResultItem;
+
+// This struct is shared between all the background workers
+typedef struct IvfSharedVector
+{
+	Oid relid;
+	Oid distfunc_oid;
+	Oid collation;
+	Oid dbid;
+	Oid userid;
+	//  directly store a full varlena Vector here
+	bool is_null;
+	char vector_data[FLEXIBLE_ARRAY_MEMBER];
+
+} IvfSharedVector;
+
+// This struct is allocated per worker.
+typedef struct IvfParallelWorkerTask
+{
+	// How many blocks have been assigned for this worker
+	int num_blocks;
+	// Semaphore to indicate the finite state of the corresponding worker. 0 = not finished, 1 = finished
+	pg_atomic_uint32 worker_done;
+	// How many results written
+	int results_count;
+	// Cursor used to return results directly from the shared memory
+	int return_result_pos;
+	// Allocated space for the block list assigned to the corresponding worker and the results
+	char data[FLEXIBLE_ARRAY_MEMBER];
+} IvfParallelWorkerTask;
+
+static IvfParallelWorkerTask **tasks;
+static dsm_segment **segments;
+static int used_workers;
+static dsm_segment *shared_info_seg;
+
+// This struct contains a list of all the block numbers (pages) that need to be scanned during query execution
+typedef struct IvfStaticScanState
+{
+	int index;
+	int total;
+	BlockNumber *blocknos;
+} IvfStaticScanState;
+
+IvfStaticScanState *scan_state;
+
+//
+typedef struct MetaBlockData
+{
+	int count;
+	BlockNumber blocknos[FLEXIBLE_ARRAY_MEMBER]; // Flexible array member
+} MetaBlockData;
+
+int result_cmp(const void *a, const void *b)
+{
+	const ResultItem *ra = (const ResultItem *)a;
+	const ResultItem *rb = (const ResultItem *)b;
+	return (ra->distance > rb->distance) - (ra->distance < rb->distance);
+}
+
+// This function is executed per worker
+void ivf_prefetch_worker_main(Datum main_arg)
+{
+
+	BackgroundWorkerUnblockSignals();
+
+	// Access the shared segment to get information about the relation and the query vector
+	dsm_handle vec_handle;
+	memcpy(&vec_handle, MyBgworkerEntry->bgw_extra, sizeof(dsm_handle));
+	dsm_segment *vec_seg = dsm_attach(vec_handle);
+	IvfSharedVector *shared_vec = dsm_segment_address(vec_seg);
+
+	// Connect to the same DB/user as the launcher
+	BackgroundWorkerInitializeConnectionByOid(shared_vec->dbid, shared_vec->userid, 0);
+
+	// Access the query vector value
+	Vector *vec = (Vector *)shared_vec->vector_data;
+	Datum value;
+
+	if (!shared_vec->is_null)
+	{
+		value = PointerGetDatum(vec);
+	}
+
+	// Access the per-worker assigned task shared memory region
+	dsm_handle handle = DatumGetUInt32(main_arg);
+	dsm_segment *seg = dsm_attach(handle);
+	IvfParallelWorkerTask *task = dsm_segment_address(seg);
+
+	StartTransactionCommand();
+	Relation rel = relation_open(shared_vec->relid, AccessShareLock);
+	int result_index = 0;
+
+	FmgrInfo procinfo;
+	fmgr_info_cxt(shared_vec->distfunc_oid, &procinfo, CurrentMemoryContext);
+	BufferAccessStrategy bas = GetAccessStrategy(BAS_BULKREAD);
+
+	BlockNumber *blocknos = (BlockNumber *)task->data;
+	ResultItem *results = (ResultItem *)(blocknos + task->num_blocks);
+
+	// Scan the assigned pages and extract the embeddings from each page
+	for (int i = 0; i < task->num_blocks; i++)
+	{
+		BlockNumber blkno = blocknos[i];
+		Buffer buf = ReadBufferExtended(rel, MAIN_FORKNUM, blkno, RBM_NORMAL, bas);
+		LockBuffer(buf, BUFFER_LOCK_SHARE);
+
+		Page page = BufferGetPage(buf);
+		OffsetNumber maxoffno = PageGetMaxOffsetNumber(page);
+		for (OffsetNumber offno = FirstOffsetNumber; offno <= maxoffno; offno++)
+		{
+			IndexTuple itup;
+			Datum datum;
+			bool isnull;
+
+			ItemId itemid = PageGetItemId(page, offno);
+			itup = (IndexTuple)PageGetItem(page, itemid);
+			datum = index_getattr(itup, 1, RelationGetDescr(rel), &isnull);
+
+			double dist = 0.0;
+			if (!shared_vec->is_null)
+			{
+				dist = DatumGetFloat8(FunctionCall2Coll(&procinfo, shared_vec->collation, datum, value));
+			}
+			results[result_index].distance = dist;
+			results[result_index].tid = itup->t_tid;
+			result_index++;
+		}
+		UnlockReleaseBuffer(buf);
+	}
+
+	// Sort the results
+	qsort(results, result_index, sizeof(ResultItem), result_cmp);
+
+	task->results_count = result_index;
+	pg_atomic_write_u32(&task->worker_done, 1);
+
+	relation_close(rel, AccessShareLock);
+	CommitTransactionCommand();
+
+	proc_exit(0);
+}
+
 /*
  * Compare list distances
  */
@@ -36,16 +213,20 @@ CompareLists(const pairingheap_node *a, const pairingheap_node *b, void *arg)
 static void
 GetScanLists(IndexScanDesc scan, Datum value)
 {
-	IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
+	IvfflatScanOpaque so = (IvfflatScanOpaque)scan->opaque;
 	BlockNumber nextblkno = IVFFLAT_HEAD_BLKNO;
-	int			listCount = 0;
-	double		maxDistance = DBL_MAX;
+	int listCount = 0;
+	double maxDistance = DBL_MAX;
 
 	/* Search all list pages */
 	while (BlockNumberIsValid(nextblkno))
 	{
-		Buffer		cbuf;
-		Page		cpage;
+
+		instr_time start, end, diff;
+		instr_time start_overhead, end_overhead, elapsed;
+
+		Buffer cbuf;
+		Page cpage;
 		OffsetNumber maxoffno;
 
 		cbuf = ReadBuffer(scan->indexRelation, nextblkno);
@@ -56,8 +237,8 @@ GetScanLists(IndexScanDesc scan, Datum value)
 
 		for (OffsetNumber offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
 		{
-			IvfflatList list = (IvfflatList) PageGetItem(cpage, PageGetItemId(cpage, offno));
-			double		distance;
+			IvfflatList list = (IvfflatList)PageGetItem(cpage, PageGetItemId(cpage, offno));
+			double distance;
 
 			/* Use procinfo from the index instead of scan key for performance */
 			distance = DatumGetFloat8(so->distfunc(so->procinfo, so->collation, PointerGetDatum(&list->center), value));
@@ -68,6 +249,8 @@ GetScanLists(IndexScanDesc scan, Datum value)
 
 				scanlist = &so->lists[listCount];
 				scanlist->startPage = list->startPage;
+				scanlist->numBlocks = list->numBlocks;
+
 				scanlist->distance = distance;
 				listCount++;
 
@@ -88,6 +271,7 @@ GetScanLists(IndexScanDesc scan, Datum value)
 				/* Reuse */
 				scanlist->startPage = list->startPage;
 				scanlist->distance = distance;
+				scanlist->numBlocks = list->numBlocks;
 				pairingheap_add(so->listQueue, &scanlist->ph_node);
 
 				/* Update max distance */
@@ -100,72 +284,95 @@ GetScanLists(IndexScanDesc scan, Datum value)
 		UnlockReleaseBuffer(cbuf);
 	}
 
+	int num_blocks = 0;
 	for (int i = listCount - 1; i >= 0; i--)
-		so->listPages[i] = GetScanList(pairingheap_remove_first(so->listQueue))->startPage;
+	{
+		IvfflatScanList *scanlist = GetScanList(pairingheap_remove_first(so->listQueue));
+		so->listPages[i] = scanlist->startPage;
+		num_blocks += scanlist->numBlocks;
+	}
+
+	scan_state = palloc(sizeof(IvfStaticScanState));
+	scan_state->index = 0;
+	scan_state->total = 0;
+	if (num_blocks > 0)
+		scan_state->blocknos = palloc(sizeof(BlockNumber) * num_blocks);
+	else
+		scan_state->blocknos = NULL;
+
+	for (int i = 0; i < listCount; i++)
+	{
+		BlockNumber searchPage = so->listPages[i];
+
+		// Walk chain of metadata pages. Each metapage contains an item which in turn contains a list of block numbers
+		while (BlockNumberIsValid(searchPage))
+		{
+			Buffer metabuf;
+			Page metapage;
+
+			metabuf = ReadBufferExtended(scan->indexRelation, MAIN_FORKNUM, searchPage, RBM_NORMAL, so->bas);
+			LockBuffer(metabuf, BUFFER_LOCK_SHARE);
+			metapage = BufferGetPage(metabuf);
+
+			ItemId itemid = PageGetItemId(metapage, FirstOffsetNumber);
+			MetaBlockData *metaDataItem = (MetaBlockData *)PageGetItem(metapage, itemid);
+
+			// Copy the block numbers to the scan_state list
+			for (int j = 0; j < metaDataItem->count; j++)
+			{
+				scan_state->blocknos[scan_state->total++] = metaDataItem->blocknos[j];
+			}
+			searchPage = IvfflatPageGetOpaque(metapage)->nextblkno;
+			UnlockReleaseBuffer(metabuf);
+		}
+	}
 
 	Assert(pairingheap_is_empty(so->listQueue));
 }
 
-/*
- * Get items
- */
-static void
-GetScanItems(IndexScanDesc scan, Datum value)
+// This function represent the serial execution. The main worker scans the list of block numbers, extracts the embeddings from each page and
+// computes the distance between each embedding and the query vector
+static void GetScanItems(IndexScanDesc scan, Datum value)
 {
-	IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
-	TupleDesc	tupdesc = RelationGetDescr(scan->indexRelation);
+	IvfflatScanOpaque so = (IvfflatScanOpaque)scan->opaque;
+	TupleDesc tupdesc = RelationGetDescr(scan->indexRelation);
 	TupleTableSlot *slot = so->vslot;
-	int			batchProbes = 0;
+	int batchProbes = 0;
 
 	tuplesort_reset(so->sortstate);
 
-	/* Search closest probes lists */
-	while (so->listIndex < so->maxProbes && (++batchProbes) <= so->probes)
+	for (int i = 0; i < scan_state->total; i++)
 	{
-		BlockNumber searchPage = so->listPages[so->listIndex++];
+		Buffer buf = ReadBufferExtended(scan->indexRelation, MAIN_FORKNUM, scan_state->blocknos[i], RBM_NORMAL, so->bas);
+		if (!BufferIsValid(buf))
+			break;
 
-		/* Search all entry pages for list */
-		while (BlockNumberIsValid(searchPage))
+		LockBuffer(buf, BUFFER_LOCK_SHARE);
+		Page page = BufferGetPage(buf);
+		OffsetNumber maxoffno = PageGetMaxOffsetNumber(page);
+
+		for (OffsetNumber offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
 		{
-			Buffer		buf;
-			Page		page;
-			OffsetNumber maxoffno;
+			IndexTuple itup;
+			Datum datum;
+			bool isnull;
 
-			buf = ReadBufferExtended(scan->indexRelation, MAIN_FORKNUM, searchPage, RBM_NORMAL, so->bas);
-			LockBuffer(buf, BUFFER_LOCK_SHARE);
-			page = BufferGetPage(buf);
-			maxoffno = PageGetMaxOffsetNumber(page);
+			ItemId itemid = PageGetItemId(page, offno);
 
-			for (OffsetNumber offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
-			{
-				IndexTuple	itup;
-				Datum		datum;
-				bool		isnull;
-				ItemId		itemid = PageGetItemId(page, offno);
-
-				itup = (IndexTuple) PageGetItem(page, itemid);
-				datum = index_getattr(itup, 1, tupdesc, &isnull);
-
-				/*
-				 * Add virtual tuple
-				 *
-				 * Use procinfo from the index instead of scan key for
-				 * performance
-				 */
-				ExecClearTuple(slot);
-				slot->tts_values[0] = so->distfunc(so->procinfo, so->collation, datum, value);
-				slot->tts_isnull[0] = false;
-				slot->tts_values[1] = PointerGetDatum(&itup->t_tid);
-				slot->tts_isnull[1] = false;
-				ExecStoreVirtualTuple(slot);
-
-				tuplesort_puttupleslot(so->sortstate, slot);
-			}
+			itup = (IndexTuple)PageGetItem(page, itemid);
+			datum = index_getattr(itup, 1, tupdesc, &isnull);
+			ExecClearTuple(slot);
+			slot->tts_values[0] = so->distfunc(so->procinfo, so->collation, datum, value);
 
-			searchPage = IvfflatPageGetOpaque(page)->nextblkno;
+			slot->tts_isnull[0] = false;
+			slot->tts_values[1] = PointerGetDatum(&itup->t_tid);
+			slot->tts_isnull[1] = false;
+			ExecStoreVirtualTuple(slot);
 
-			UnlockReleaseBuffer(buf);
+			tuplesort_puttupleslot(so->sortstate, slot);
 		}
+
+		UnlockReleaseBuffer(buf);
 	}
 
 	tuplesort_performsort(so->sortstate);
@@ -175,6 +382,121 @@ GetScanItems(IndexScanDesc scan, Datum value)
 #endif
 }
 
+static void
+ParallelGetScanItems(IndexScanDesc scan, Datum value)
+{
+	IvfflatScanOpaque so = (IvfflatScanOpaque)scan->opaque;
+	TupleDesc tupdesc = RelationGetDescr(scan->indexRelation);
+	TupleTableSlot *slot = so->vslot;
+	int batchProbes = 0;
+
+	tuplesort_reset(so->sortstate);
+
+	// Create a shared structure that contains information shared to all the background workers
+	Vector *qvec = NULL;
+	if (DatumGetPointer(value) != NULL)
+	{
+		qvec = DatumGetVector(value);
+	}
+	int dim = so->dimensions;
+
+	// Compute shared memory size and create the DSM segment
+	Size sz = offsetof(IvfSharedVector, vector_data) + VECTOR_SIZE(dim);
+	shared_info_seg = dsm_create(sz, 0);
+	dsm_handle vec_handle = dsm_segment_handle(shared_info_seg);
+
+	// Get pointer to shared memory
+	IvfSharedVector *shared_vec = dsm_segment_address(shared_info_seg);
+	shared_vec->relid = RelationGetRelid(scan->indexRelation);
+	shared_vec->distfunc_oid = so->procinfo->fn_oid;
+	shared_vec->collation = so->collation;
+	shared_vec->dbid = MyDatabaseId;
+	shared_vec->userid = GetUserId();
+
+	Vector *vec_in_dsm = (Vector *)shared_vec->vector_data;
+
+	if (qvec != NULL)
+	{
+		// Copy the query vector to the shared structure
+		shared_vec->is_null = false;
+		SET_VARSIZE(vec_in_dsm, VECTOR_SIZE(dim));
+		vec_in_dsm->dim = dim;
+		memcpy(vec_in_dsm->x, qvec->x, sizeof(float4) * dim);
+	}
+	else
+	{
+		// Notify the background workers in case the query vector is NULL
+		shared_vec->is_null = true;
+	}
+
+	tasks = (IvfParallelWorkerTask **)palloc(NUM_WORKERS * sizeof(IvfParallelWorkerTask *));
+	segments = (dsm_segment **)palloc(NUM_WORKERS * sizeof(dsm_segment *));
+
+	int chunk_size = (scan_state->total + NUM_WORKERS - 1) / NUM_WORKERS;
+	BackgroundWorkerHandle *handles[NUM_WORKERS];
+
+	// Generate NUM_WORKERS background processes. Assign a chunk of the block list to each worker.
+	for (int w = 0; w < NUM_WORKERS; w++)
+	{
+		int start = w * chunk_size;
+		int end = Min(start + chunk_size, scan_state->total);
+		int count = end - start;
+
+		if (count <= 0)
+		{
+			break;
+		}
+		used_workers++;
+		int max_results = count * ((BLCKSZ - SizeOfPageHeaderData) / (dim * sizeof(float)));
+		Size sz = offsetof(IvfParallelWorkerTask, data) + (sizeof(BlockNumber) * count) + (sizeof(ResultItem) * max_results);
+		segments[w] = dsm_create(sz, 0);
+		tasks[w] = dsm_segment_address(segments[w]);
+		tasks[w]->num_blocks = count;
+		tasks[w]->return_result_pos = 0;
+		pg_atomic_init_u32(&tasks[w]->worker_done, 0);
+		memcpy(tasks[w]->data, &scan_state->blocknos[start], sizeof(BlockNumber) * count);
+		tasks[w]->results_count = 0;
+
+		// Launch worker
+		BackgroundWorker worker;
+		memset(&worker, 0, sizeof(worker));
+		worker.bgw_flags = BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION;
+		worker.bgw_start_time = BgWorkerStart_ConsistentState;
+		worker.bgw_restart_time = BGW_NEVER_RESTART;
+		// Pass a pointer to the struct that is shared between all the workers
+		memcpy(worker.bgw_extra, &vec_handle, sizeof(vec_handle));
+		snprintf(worker.bgw_name, BGW_MAXLEN, "ivfflat worker %d", w);
+		snprintf(worker.bgw_library_name, BGW_MAXLEN, "vector");
+		snprintf(worker.bgw_function_name, BGW_MAXLEN, "ivf_prefetch_worker_main");
+		worker.bgw_main_arg = UInt32GetDatum(dsm_segment_handle(segments[w]));
+
+		if (!RegisterDynamicBackgroundWorker(&worker, &handles[w]))
+			elog(INFO, "could not register worker %d", w);
+	}
+
+	// Wait until all the workers have been finished
+	bool all_done = false;
+	while (!all_done)
+	{
+		all_done = true;
+		for (int w = 0; w < used_workers; w++)
+		{
+			if (pg_atomic_read_u32(&tasks[w]->worker_done) == 0)
+			{
+				all_done = false;
+				break;
+			}
+		}
+		if (!all_done)
+			pg_usleep(1000);
+	}
+
+	tuplesort_performsort(so->sortstate);
+#if defined(IVFFLAT_MEMORY)
+	elog(INFO, "memory: %zu MB", MemoryContextMemAllocated(CurrentMemoryContext, true) / (1024 * 1024));
+#endif
+}
+
 /*
  * Zero distance
  */
@@ -190,8 +512,9 @@ ZeroDistance(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
 static Datum
 GetScanValue(IndexScanDesc scan)
 {
-	IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
-	Datum		value;
+
+	IvfflatScanOpaque so = (IvfflatScanOpaque)scan->opaque;
+	Datum value;
 
 	if (scan->orderByData->sk_flags & SK_ISNULL)
 	{
@@ -227,10 +550,10 @@ GetScanValue(IndexScanDesc scan)
 static Tuplesortstate *
 InitScanSortState(TupleDesc tupdesc)
 {
-	AttrNumber	attNums[] = {1};
-	Oid			sortOperators[] = {Float8LessOperator};
-	Oid			sortCollations[] = {InvalidOid};
-	bool		nullsFirstFlags[] = {false};
+	AttrNumber attNums[] = {1};
+	Oid sortOperators[] = {Float8LessOperator};
+	Oid sortCollations[] = {InvalidOid};
+	bool nullsFirstFlags[] = {false};
 
 	return tuplesort_begin_heap(tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, work_mem, NULL, false);
 }
@@ -243,12 +566,15 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
 {
 	IndexScanDesc scan;
 	IvfflatScanOpaque so;
-	int			lists;
-	int			dimensions;
-	int			probes = ivfflat_probes;
-	int			maxProbes;
+	int lists;
+	int dimensions;
+	int probes = ivfflat_probes;
+	int maxProbes;
 	MemoryContext oldCtx;
 
+	init_num_workers();
+	used_workers = 0;
+
 	scan = RelationGetIndexScan(index, nkeys, norderbys);
 
 	/* Get lists and dimensions from metapage */
@@ -265,7 +591,7 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
 	if (maxProbes > lists)
 		maxProbes = lists;
 
-	so = (IvfflatScanOpaque) palloc(sizeof(IvfflatScanOpaqueData));
+	so = (IvfflatScanOpaque)palloc(sizeof(IvfflatScanOpaqueData));
 	so->typeInfo = IvfflatGetTypeInfo(index);
 	so->first = true;
 	so->probes = probes;
@@ -285,8 +611,8 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
 
 	/* Create tuple description for sorting */
 	so->tupdesc = CreateTemplateTupleDesc(2);
-	TupleDescInitEntry(so->tupdesc, (AttrNumber) 1, "distance", FLOAT8OID, -1, 0);
-	TupleDescInitEntry(so->tupdesc, (AttrNumber) 2, "heaptid", TIDOID, -1, 0);
+	TupleDescInitEntry(so->tupdesc, (AttrNumber)1, "distance", FLOAT8OID, -1, 0);
+	TupleDescInitEntry(so->tupdesc, (AttrNumber)2, "heaptid", TIDOID, -1, 0);
 
 	/* Prep sort */
 	so->sortstate = InitScanSortState(so->tupdesc);
@@ -317,10 +643,9 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
 /*
  * Start or restart an index scan
  */
-void
-ivfflatrescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
+void ivfflatrescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys)
 {
-	IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
+	IvfflatScanOpaque so = (IvfflatScanOpaque)scan->opaque;
 
 	so->first = true;
 	pairingheap_reset(so->listQueue);
@@ -336,12 +661,11 @@ ivfflatrescan(IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int
 /*
  * Fetch the next tuple in the given scan
  */
-bool
-ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
+bool ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
 {
-	IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
+	IvfflatScanOpaque so = (IvfflatScanOpaque)scan->opaque;
 	ItemPointer heaptid;
-	bool		isnull;
+	bool isnull;
 
 	/*
 	 * Index can be used to scan backward, but Postgres doesn't support
@@ -351,7 +675,8 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
 
 	if (so->first)
 	{
-		Datum		value;
+
+		Datum value;
 
 		/* Count index scan for stats */
 		pgstat_count_index_scan(scan->indexRelation);
@@ -366,35 +691,101 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
 			elog(ERROR, "non-MVCC snapshots are not supported with ivfflat");
 
 		value = GetScanValue(scan);
-		IvfflatBench("GetScanLists", GetScanLists(scan, value));
-		IvfflatBench("GetScanItems", GetScanItems(scan, value));
+
+		struct timespec start, end;
+		double elapsed;
+
+		GetScanLists(scan, value);
+		if (NUM_WORKERS > 0)
+		{
+			// Apply parallel index scan
+			ParallelGetScanItems(scan, value);
+		}
+		else
+		{
+			// Apply sequential index scan
+			GetScanItems(scan, value);
+		}
+
 		so->first = false;
 		so->value = value;
 	}
 
-	while (!tuplesort_gettupleslot(so->sortstate, true, false, so->mslot, NULL))
+	if (NUM_WORKERS > 0)
 	{
-		if (so->listIndex == so->maxProbes)
+		// Keep a cursor to the result list of each worker in the shared memory.
+		// Perform at most #worker comparisons and return the result from the worker that has the smallest distance to the query vector
+		int best_worker = -1;
+		double best_distance = DBL_MAX;
+
+		for (int w = 0; w < used_workers; w++)
+		{
+			if (tasks[w]->return_result_pos < tasks[w]->results_count)
+			{
+				BlockNumber *blocknos = (BlockNumber *)tasks[w]->data;
+				ResultItem *results = (ResultItem *)(blocknos + tasks[w]->num_blocks);
+
+				double dist = results[tasks[w]->return_result_pos].distance;
+				if (dist < best_distance)
+				{
+					best_distance = dist;
+					best_worker = w;
+				}
+			}
+		}
+
+		// No more results
+		if (best_worker == -1)
+		{
 			return false;
+		}
+
+		BlockNumber *blocknos = (BlockNumber *)tasks[best_worker]->data;
+		ResultItem *results = (ResultItem *)(blocknos + tasks[best_worker]->num_blocks);
+		ResultItem *item = &results[tasks[best_worker]->return_result_pos++];
 
-		IvfflatBench("GetScanItems", GetScanItems(scan, so->value));
+		scan->xs_heaptid = item->tid;
+		scan->xs_recheck = false;
+		scan->xs_recheckorderby = false;
 	}
+	else
+	{
+		// No more results
+		if (!tuplesort_gettupleslot(so->sortstate, true, false, so->mslot, NULL))
+		{
+			return false;
+		}
+
+		Datum distDatum = slot_getattr(so->mslot, 1, &isnull);
+		heaptid = (ItemPointer)DatumGetPointer(slot_getattr(so->mslot, 2, &isnull));
 
-	heaptid = (ItemPointer) DatumGetPointer(slot_getattr(so->mslot, 2, &isnull));
+		scan->xs_heaptid = *heaptid;
+		scan->xs_recheck = false;
+		scan->xs_recheckorderby = false;
+	}
 
-	scan->xs_heaptid = *heaptid;
-	scan->xs_recheck = false;
-	scan->xs_recheckorderby = false;
 	return true;
 }
 
 /*
  * End a scan and release resources
  */
-void
-ivfflatendscan(IndexScanDesc scan)
+void ivfflatendscan(IndexScanDesc scan)
 {
-	IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
+	// Deallocate the reserved space in case parallel algorithm executed
+	if (NUM_WORKERS > 0)
+	{
+		for (int w = 0; w < used_workers; w++)
+		{
+			dsm_detach(segments[w]);
+		}
+		dsm_detach(shared_info_seg);
+
+		pfree(tasks);
+		pfree(segments);
+	}
+
+	IvfflatScanOpaque so = (IvfflatScanOpaque)scan->opaque;
 
 	/* Free any temporary files */
 	tuplesort_end(so->sortstate);
diff --git a/src/ivfutils.c b/src/ivfutils.c
index 9596391be..d5a22e559 100644
--- a/src/ivfutils.c
+++ b/src/ivfutils.c
@@ -188,7 +188,7 @@ IvfflatGetMetaPageInfo(Relation index, int *lists, int *dimensions)
 void
 IvfflatUpdateList(Relation index, ListInfo listInfo,
 				  BlockNumber insertPage, BlockNumber originalInsertPage,
-				  BlockNumber startPage, ForkNumber forkNum)
+				  BlockNumber startPage, int numBlocks, ForkNumber forkNum)
 {
 	Buffer		buf;
 	Page		page;
@@ -219,6 +219,9 @@ IvfflatUpdateList(Relation index, ListInfo listInfo,
 		changed = true;
 	}
 
+	list->numBlocks=numBlocks;
+	changed=true;
+
 	/* Only commit if changed */
 	if (changed)
 		IvfflatCommitBuffer(buf, state);
@@ -259,8 +262,8 @@ VectorUpdateCenter(Pointer v, int dimensions, float *x)
 	SET_VARSIZE(vec, VECTOR_SIZE(dimensions));
 	vec->dim = dimensions;
 
-	for (int i = 0; i < dimensions; i++)
-		vec->x[i] = x[i];
+	for (int k = 0; k < dimensions; k++)
+		vec->x[k] = x[k];
 }
 
 static void
@@ -271,8 +274,8 @@ HalfvecUpdateCenter(Pointer v, int dimensions, float *x)
 	SET_VARSIZE(vec, HALFVEC_SIZE(dimensions));
 	vec->dim = dimensions;
 
-	for (int i = 0; i < dimensions; i++)
-		vec->x[i] = Float4ToHalfUnchecked(x[i]);
+	for (int k = 0; k < dimensions; k++)
+		vec->x[k] = Float4ToHalfUnchecked(x[k]);
 }
 
 static void
@@ -284,33 +287,29 @@ BitUpdateCenter(Pointer v, int dimensions, float *x)
 	SET_VARSIZE(vec, VARBITTOTALLEN(dimensions));
 	VARBITLEN(vec) = dimensions;
 
-	for (uint32 i = 0; i < VARBITBYTES(vec); i++)
-		nx[i] = 0;
+	for (uint32 k = 0; k < VARBITBYTES(vec); k++)
+		nx[k] = 0;
 
-	for (int i = 0; i < dimensions; i++)
-		nx[i / 8] |= (x[i] > 0.5 ? 1 : 0) << (7 - (i % 8));
+	for (int k = 0; k < dimensions; k++)
+		nx[k / 8] |= (x[k] > 0.5 ? 1 : 0) << (7 - (k % 8));
 }
 
 static void
 VectorSumCenter(Pointer v, float *x)
 {
 	Vector	   *vec = (Vector *) v;
-	int			dim = vec->dim;
 
-	/* Auto-vectorized */
-	for (int i = 0; i < dim; i++)
-		x[i] += vec->x[i];
+	for (int k = 0; k < vec->dim; k++)
+		x[k] += vec->x[k];
 }
 
 static void
 HalfvecSumCenter(Pointer v, float *x)
 {
 	HalfVector *vec = (HalfVector *) v;
-	int			dim = vec->dim;
 
-	/* Auto-vectorized on aarch64 */
-	for (int i = 0; i < dim; i++)
-		x[i] += HalfToFloat4(vec->x[i]);
+	for (int k = 0; k < vec->dim; k++)
+		x[k] += HalfToFloat4(vec->x[k]);
 }
 
 static void
@@ -318,8 +317,8 @@ BitSumCenter(Pointer v, float *x)
 {
 	VarBit	   *vec = (VarBit *) v;
 
-	for (int i = 0; i < VARBITLEN(vec); i++)
-		x[i] += (float) (((VARBITS(vec)[i / 8]) >> (7 - (i % 8))) & 0x01);
+	for (int k = 0; k < VARBITLEN(vec); k++)
+		x[k] += (float) (((VARBITS(vec)[k / 8]) >> (7 - (k % 8))) & 0x01);
 }
 
 /*
diff --git a/src/ivfvacuum.c b/src/ivfvacuum.c
index 750cdd65a..2181b7be4 100644
--- a/src/ivfvacuum.c
+++ b/src/ivfvacuum.c
@@ -129,7 +129,7 @@ ivfflatbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats,
 			if (BlockNumberIsValid(insertPage))
 			{
 				listInfo.offno = coffno;
-				IvfflatUpdateList(index, listInfo, insertPage, InvalidBlockNumber, InvalidBlockNumber, MAIN_FORKNUM);
+				IvfflatUpdateList(index, listInfo, insertPage, InvalidBlockNumber, InvalidBlockNumber, 0,MAIN_FORKNUM);
 			}
 		}
 	}
