Skip to content

Commit 4bc6fb5

Browse files
committed
Fix integer overflow bug in GiST buffering build calculations.
The result of (maintenance_work_mem * 1024) / BLCKSZ doesn't fit in a signed 32-bit integer, if maintenance_work_mem >= 2GB. Use double instead. And while we're at it, write the calculations in an easier to understand form, with the intermediary steps written out and commented.
1 parent 2755abf commit 4bc6fb5

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

src/backend/access/gist/gistbuild.c

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -323,8 +323,8 @@ gistInitBuffering(GISTBuildState *buildstate)
323323
* calculating levelStep is very close to Arge et al's formula. For a
324324
* large B, our formula gives a value that is 2x higher.
325325
*
326-
* The average size of a subtree of depth n can be calculated as a
327-
* geometric series:
326+
* The average size (in pages) of a subtree of depth n can be calculated
327+
* as a geometric series:
328328
*
329329
* B^0 + B^1 + B^2 + ... + B^n = (1 - B^(n + 1)) / (1 - B)
330330
*
@@ -353,14 +353,28 @@ gistInitBuffering(GISTBuildState *buildstate)
353353
* the hash table.
354354
*/
355355
levelStep = 1;
356-
while (
357-
/* subtree must fit in cache (with safety factor of 4) */
358-
(1 - pow(avgIndexTuplesPerPage, (double) (levelStep + 1))) / (1 - avgIndexTuplesPerPage) < effective_cache_size / 4
359-
&&
360-
/* each node in the lowest level of a subtree has one page in memory */
361-
(pow(maxIndexTuplesPerPage, (double) levelStep) < (maintenance_work_mem * 1024) / BLCKSZ)
362-
)
356+
for (;;)
363357
{
358+
double subtreesize;
359+
double maxlowestlevelpages;
360+
361+
/* size of an average subtree at this levelStep (in pages). */
362+
subtreesize =
363+
(1 - pow(avgIndexTuplesPerPage, (double) (levelStep + 1))) /
364+
(1 - avgIndexTuplesPerPage);
365+
366+
/* max number of pages at the lowest level of a subtree */
367+
maxlowestlevelpages = pow(maxIndexTuplesPerPage, (double) levelStep);
368+
369+
/* subtree must fit in cache (with safety factor of 4) */
370+
if (subtreesize > effective_cache_size / 4)
371+
break;
372+
373+
/* each node in the lowest level of a subtree has one page in memory */
374+
if (maxlowestlevelpages > ((double) maintenance_work_mem * 1024) / BLCKSZ)
375+
break;
376+
377+
/* Good, we can handle this levelStep. See if we can go one higher. */
364378
levelStep++;
365379
}
366380

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy