From cbabf50dccc29aed456a56ae8909d4d593c3ab38 Mon Sep 17 00:00:00 2001 From: Tom Lane Date: Fri, 14 Jun 2013 14:26:50 -0400 Subject: Avoid deadlocks during insertion into SP-GiST indexes. SP-GiST's original scheme for avoiding deadlocks during concurrent index insertions doesn't work, as per report from Hailong Li, and there isn't any evident way to make it work completely. We could possibly lock individual inner tuples instead of their whole pages, but preliminary experimentation suggests that the performance penalty would be huge. Instead, if we fail to get a buffer lock while descending the tree, just restart the tree descent altogether. We keep the old tuple positioning rules, though, in hopes of reducing the number of cases where this can happen. Teodor Sigaev, somewhat edited by Tom Lane --- src/backend/access/spgist/spginsert.c | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) (limited to 'src/backend/access/spgist/spginsert.c') diff --git a/src/backend/access/spgist/spginsert.c b/src/backend/access/spgist/spginsert.c index 456a71fbba5..b20ddcc79a3 100644 --- a/src/backend/access/spgist/spginsert.c +++ b/src/backend/access/spgist/spginsert.c @@ -43,7 +43,10 @@ spgistBuildCallback(Relation index, HeapTuple htup, Datum *values, /* Work in temp context, and reset it after each tuple */ oldCtx = MemoryContextSwitchTo(buildstate->tmpCtx); - spgdoinsert(index, &buildstate->spgstate, &htup->t_self, *values, *isnull); + /* No concurrent insertions can be happening, so failure is unexpected */ + if (!spgdoinsert(index, &buildstate->spgstate, &htup->t_self, + *values, *isnull)) + elog(ERROR, "unexpected spgdoinsert() failure"); MemoryContextSwitchTo(oldCtx); MemoryContextReset(buildstate->tmpCtx); @@ -217,7 +220,17 @@ spginsert(PG_FUNCTION_ARGS) initSpGistState(&spgstate, index); - spgdoinsert(index, &spgstate, ht_ctid, *values, *isnull); + /* + * We might have to repeat spgdoinsert() multiple times, if conflicts + * occur with concurrent insertions. If so, reset the insertCtx each time + * to avoid cumulative memory consumption. That means we also have to + * redo initSpGistState(), but it's cheap enough not to matter. + */ + while (!spgdoinsert(index, &spgstate, ht_ctid, *values, *isnull)) + { + MemoryContextReset(insertCtx); + initSpGistState(&spgstate, index); + } SpGistUpdateMetaPage(index); -- cgit v1.2.3